Pages

Ads 468x60px

Thursday, July 26, 2012

IBM: LDAP, WAS, WebSEAL Start Commands and Default Values



It will help you to start and verify LDAP, WAS, WebSEAL status. Here, I used default values for everything.

1-Verify Webseal Status:
  $pdweb status

Verify LDAP, WAS, Webseal Status:
  $pd_start status

2-Start WebSphere Application Server (WAS):
  $cd /opt/IBM/WebSphere/AppServer/profiles/AppSrv01/bin
  $./startServer.sh server1    //server1 is the WAS instance name

3-Start LDAP:
  $cd /opt/ibm/ldap/V6.1/sbin/
  $ibmslapd

4-Start Webseal:
  $cd /opt/pdweb/bin
  $pdweb start

5-Verify Webseal Status (again):
  $pdweb status

Verify LDAP, WAS, Webseal Status (again):
  $pd_start status


6-TDS URL(LDAP):
  http://tameb:9080/IDSWebApp/IDSjsp/Login.jsp

Note: Here 'tameb' is the hostname. It should be written in /etc/hosts to resolve like
tameb 192.168.179.131

Username Password
superadmin secret
cn=root object00

7-WAS Console:
  http://tameb:9060/ibm/console/

Admin Username Password
admin sec_master object00

LDAP/TDS Default Information:

Attribute Values
LDAP Hostname tameb:389 or your_IP:389
User DN cn=root
Password object00
Non-SSL Port 389
SSL Port 636
SSL key file /opt/ibm/ldap/V6.1/lib/am_key.kdb

Java: IBM Tivoli Access Manager (ITAM-eb) Default Password Validation



These are the following IBM Tivoli Access Manager (ITAM-eb)  password policy parameters and the default values:

Parameter                                 Default Value
min-password-length                         8

min-password-alphas                         4

min-password-non-alphas                 1

max-password-repeated-chars         2

password-spaces                            not set

If you are using IBM Tivoli Directory Server (ITDS) integrated with ITAM-eb, then you can see its password guidelines here:
http://pic.dhe.ibm.com/infocenter/tivihelp/v2r1/index.jsp?topic=%2Fcom.ibm.IBMDS.doc%2Fadmin_gd198.htm

This class will help you for IBM Tivoli Access Manager (ITAM-eb)  password validation and user email validation.



import java.util.regex.Matcher;
import java.util.regex.Pattern;

// for validations of password
public class Validation {

// email regular expression
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

// validate password length
public static boolean passwordLength(String pwd) {
boolean length = false;

if (pwd.length() >= 8) {
length = true;
}
return length;
}

// validate password's count of alpha characters
public static boolean passwordAlphaCount(String pwd) {
boolean alpha = false;
int count = 0;

try {

for (int i = 0; i < pwd.length(); i++) {
if (Character.isLetter(pwd.charAt(i)))
++count;
}

if (count >= 4)
alpha = true;
} catch (Exception ex) {

}
return alpha;
}

// validate password's count of non alpha characters
public static boolean passwordNonAlphaCount(String pwd) {
boolean nonalpha = false;
int count = 0;

try {

for (int i = 0; i < pwd.length(); i++) {
if (Character.isDigit(pwd.charAt(i)))
++count;
}

if (count >= 1)
nonalpha = true;
} catch (Exception ex) {

}
return nonalpha;
}

// validate password's repetition of characters
public static boolean passwordCharRepeat(String pwd) {
boolean repeat = true;

for (int i = 2; i < pwd.length(); i++) {

if (String.valueOf(pwd.charAt(i - 2)).equals(String.valueOf(pwd.charAt(i - 1)))
&& String.valueOf(pwd.charAt(i - 1)).equals(String.valueOf(pwd.charAt(i ))))
repeat = false;
}
return repeat;
}

// validate IBM Tivoli Access Manager user email
public static boolean emailValidate(final String email) {

Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
}


Java: Get/Set Valid User Account of IBM Tivoli Access Manager (ITAM-eb)


This will help you to get/set valid user account of IBM Tivoli Access Manager (ITAM-eb) using TAM Java API. Please configure your environment before running this. Your PATH, CLASSPATH, JAVAHOME environmental variables should be set before running this and you have to include PD.jar in your project and classpath. Configuration for TAM-eb should be correct otherwise there will be some problems with it. For conection with IBM Tivoli Access Manager (ITAM-eb) visit:   http://usmanali112.blogspot.com/2012/07/java-connection-with-ibm-tivoli-access.html



import com.tivoli.pd.jadmin.PDUser;
import com.tivoli.pd.jutil.PDContext;
import com.tivoli.pd.jutil.PDMessages;

// service for TAM user
public class UserService {

private PDMessages msgs = new PDMessages();

// to get user account is valid or invalid
public boolean getValidAccount(String name) {
boolean valid = false;

try {
   // Initialize administration API Context
   ctxt = TAMConnection.InitializeContext();
PDUser pdUser = new PDUser(ctxt, name, msgs);
valid = pdUser.isAccountValid();
// Close administration API Context
TAMConnection.CloseContext(msgs);
}catch (Exception ex) {
ex.getMessage();
}
return valid;
}

// to set user account to valid or invalid
public void setValidAccount(String name, boolean valid) {
PDContext ctxt = null;

try {
// Initialize administration API Context
ctxt = TAMConnection.InitializeContext();
PDUser pdUser = new PDUser(ctxt, name, msgs);
pdUser.setAccountValid(ctxt, valid, msgs);
System.out.println(pdUser.isAccountValid());
// Close administration API Context
TAMConnection.CloseContext(msgs);

} catch (Exception ex) {
ex.getMessage();
}
}
}

Java: Set User Password and Show Users list of IBM Tivoli Access Manager (ITAM-eb)


This will help you to set user password and show all users list of IBM Tivoli Access Manager (ITAM-eb) using TAM Java API. Please configure your environment before running this. Your PATH, CLASSPATH, JAVAHOME environmental variables should be set before running this and you have to include PD.jar in your project and classpath. Configuration for TAM-eb should be correct otherwise there will be some problems with it. For conection with IBM Tivoli Access Manager (ITAM-eb) visit:   http://usmanali112.blogspot.com/2012/07/java-connection-with-ibm-tivoli-access.html



import java.util.ArrayList;
import com.tivoli.pd.jadmin.PDUser;
import com.tivoli.pd.jutil.PDContext;
import com.tivoli.pd.jutil.PDMessages;

// service for TAM user
public class UserService {

private PDMessages msgs = new PDMessages();

// to get list of all users
public ArrayList<String> listUser() {
PDContext ctxt = null;
ArrayList<String> list = null;

try {
// Initialize administration API Context
ctxt = TAMConnection.InitializeContext();
list = PDUser.listUsers(ctxt,
PDUser.PDUSER_ALLPATTERN, PDUser.PDUSER_MAXRETURN, false,
msgs); // (context, pattern, maximum return, list by
// registry name, messages)
// Close administration API Context
TAMConnection.CloseContext(msgs);

} catch (Exception ex) {
ex.getMessage();
}
return list;
}

// to set TAM user password
public void setPassword(String name, String password) {
PDContext ctxt = null;

try {
// Initialize administration API Context
ctxt = TAMConnection.InitializeContext();
PDUser pdUser = new PDUser(ctxt, name, msgs);
pdUser.setPassword(ctxt, password.toCharArray(), msgs);
// Close administration API Context
TAMConnection.CloseContext(msgs);
} catch (Exception ex) {
ex.getMessage();
}
}
}

Java: Add/Delete User of IBM Tivoli Access Manager (ITAM-eb)


This will help you to add/delete user of IBM Tivoli Access Manager (ITAM-eb) using TAM Java API. Please configure your environment before running this. Your PATH, CLASSPATH, JAVAHOME environmental variables should be set before running this and you have to include PD.jar in your project and classpath. Configuration for TAM-eb should be correct otherwise there will be some problems with it. I used default values here which you have to change according to your requirements. For conection with IBM Tivoli Access Manager (ITAM-eb) visit:   http://usmanali112.blogspot.com/2012/07/java-connection-with-ibm-tivoli-access.html



import com.tivoli.pd.jadmin.PDUser;
import com.tivoli.pd.jutil.PDContext;
import com.tivoli.pd.jutil.PDMessages;
import com.tivoli.pd.jutil.PDRgyUserName;

// service for TAM user
public class UserService {

// to set default values for User services
private String rgySuffix = "c=us";
private PDMessages msgs = new PDMessages();

// create user in TAM
public void createUser(String firstName, String lastName,
String password, String group) {
PDContext ctxt = null;
PDRgyUserName pdRgyUserName = null;

ArrayList<String> groupList = new ArrayList<String>();

// Set default values to create user
String name = firstName + " " + lastName;
boolean ssoUser = true;
boolean pwdPolicy = true;

try {

// Initialize administration API Context
ctxt = TAMConnection.InitializeContext();
String rgyName = "cn=" + name + "," + rgySuffix;
pdRgyUserName = new PDRgyUserName(rgyName, firstName, lastName);
groupList.add(group);
PDUser.createUser(ctxt, name, pdRgyUserName, null,
password.toCharArray(), groupList, ssoUser, pwdPolicy,
msgs);
PDUser pdUser = new PDUser(ctxt, name, msgs);
pdUser.setAccountValid(ctxt, true, msgs);
// Close administration API Context
TAMConnection.CloseContext(msgs);
}catch (Exception ex) {
ex.getMessage();
}
return result;
}

// to delete TAM user
public void deleteUser(String name) {
PDContext ctxt = null;

try {
// Initialize administration API Context
ctxt = TAMConnection.InitializeContext();
PDUser.deleteUser(ctxt, name, true, msgs);
// Close administration API Context
TAMConnection.CloseContext(msgs);

} catch (Exception ex) {
ex.getMessage();
}
}
}

Java: Add/Delete Group and Show Groups list of IBM Tivoli Access Manager (ITAM-eb)


This will help you to add/delete group and get all groups list of IBM Tivoli Access Manager (ITAM-eb) using TAM Java API. Please configure your environment before running this. Your PATH, CLASSPATH, JAVAHOME environmental variables should be set before running this and you have to include PD.jar in your project and classpath. Configuration for TAM-eb should be correct otherwise there will be some problems with it. I used default values here which you have to change according to your requirements. For conection with IBM Tivoli Access Manager (ITAM-eb) visit:   http://usmanali112.blogspot.com/2012/07/java-connection-with-ibm-tivoli-access.html


import java.util.ArrayList;
import com.tivoli.pd.jadmin.PDGroup;
import com.tivoli.pd.jutil.PDContext;
import com.tivoli.pd.jutil.PDMessages;
import com.tivoli.pd.jutil.PDRgyGroupName;

// service for the TAM groups
public class GroupService {

private String rgySuffix = "c=us";
private PDMessages msgs = new PDMessages();

// create group in TAM
public void createGroup(String group) {
PDContext ctxt = null;
try {
ctxt = TAMConnection.InitializeContext();
this.rgySuffix = TAMConnection.registrysuffix;
String rgyGroup = "cn=" + group + "," + rgySuffix;
PDRgyGroupName pdRgyGroupName = new PDRgyGroupName(rgyGroup);
PDGroup.createGroup(ctxt, group, pdRgyGroupName, null, null, msgs);
TAMConnection.CloseContext(msgs);
} catch (Exception ex) {
ex.getMessage();
}

}

// to delete group from TAM
public void deleteGroup(String group) {
PDContext ctxt = null;

try {
ctxt = TAMConnection.InitializeContext();
PDGroup.deleteGroup(ctxt, group, true, msgs);
TAMConnection.CloseContext(msgs);

} catch (Exception ex) {
ex.getMessage();
}
}

// to get all groups from TAM
public ArrayList<String> getGroup() {
PDContext ctxt = null;
                ArrayList<String> list = null;
try {
ctxt = TAMConnection.InitializeContext();
list = PDGroup.listGroups(ctxt,
PDGroup.PDGROUP_ALLPATTERN, PDGroup.PDGROUP_MAXRETURN,
true, msgs);

TAMConnection.CloseContext(msgs);
}  catch (Exception ex) {
ex.getMessage();
}
return list;
}
}

Wednesday, July 25, 2012

Java: Connection with IBM Tivoli Access Manager (ITAM-eb)

This will help you to create connection with IBM Tivoli Access Manager (ITAM-eb) using TAM Java API. Please configure your environment before running this. Your PATH, CLASSPATH, JAVAHOME environmental variables should be set before running this and you have to include PD.jar in your project and classpath. Configuration for TAM-eb should be correct otherwise there will be some problems with it. I have used default values for the connection, so you can modify these according your environment settings. The most important part is the use of com.tivoli.pd.jcfg.SvrSslCfg utility.


import java.util.*;
import java.net.URL;

import com.tivoli.pd.jutil.PDContext;
import com.tivoli.pd.jadmin.*;

// to connect TAM
public class TAMConnection {

// Set up values for TAM Context Initialization
private static PDContext ctxt = null;
private PDMessages msgs = new PDMessages();

// Set up default values for TAM connection and change all values according to your environment
//app.properties will be generated with com.tivoli.pd.jcfg.SvrSslCfg utility
private static String prog           = "TAMConnection";
private static String adminName      = "sec_master";
private static String configURLStr   = "file:///root/Desktop/app.properties";
private static String registrysuffix = "c=us";
private static char[] adminPassword  = {'o','b','j','e','c','t','0','0','\0'};
private Locale locale                = new Locale("ENGLISH", "US");
private URL configURL                = null;

private TAMConnection() {
try {

PDAdmin.initialize(prog, msgs);
configURL = new URL(configURLStr);
ctxt = new PDContext(locale, adminName, adminPassword, configURL);
} catch (Exception ex) {
ex.getMessage();
}
}

// to initialize the TAM context
public static PDContext InitializeContext() {
new TAMConnection();
return ctxt;
}

// to close the TAM context
public static void CloseContext(PDMessages msgs) {
try {
if (ctxt != null) {
ctxt.close();
}

PDAdmin.shutdown(msgs);
} catch (Exception ex) {
ex.getMessage();
}
}
}

Java: Modify User Attributes in IBM Tivoli Directory Server (TDS) LDAP using JNDI

It will help you to modify user attribute (add, replace, delete) in IBM Tivoli Directory Server (TDS) using JNDI. I used default values, so you have to change it according your requirements. Also the user attributes will depend upon your directory server schema.For connection with IBM Tivoli Directory Server (TDS)/ LDAP visit: http://usmanali112.blogspot.com/2012/07/java-authentication-and-connection-with.html



import javax.naming.ldap.InitialLdapContext;
import javax.naming.directory.*;

//this class perform all LDAP actions for the user
public class LDAPService {

private String base = "c=us"; // base for LDAP
private String realm = "cn=realm1"; // LDAP realm for user
     
// to set user password
public void setPassword(String surname, String password) {

try {
// Set up default values for LDAP information
String distinguish_name = "sn=" + surname + "," + realm + ","
+ base;

// Initialize LDAP Context
InitialLdapContext context = LDAPConnection.InitializeContext();

ModificationItem[] mods = new ModificationItem[1];
Attribute mod0 = new BasicAttribute("userpassword", password);
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, mod0);
                       //use DirContext.ADD_ATTRIBUTE to add an attribute
//use DirContext.DELETE_ATTRIBUTE to delete an attribute

// Perform modification of user
context.modifyAttributes(distinguish_name, mods);

// Close LDAP Context
LDAPConnection.CloseContext();

} catch (Exception ex) {
ex.getMessage();
}
}
}

Java: Search User in IBM Tivoli Directory Server (TDS) LDAP using JNDI

It will help you to search user and other entries in IBM Tivoli Directory Server (TDS) using JNDI. I used default values, so you have to change it according your requirements. Also the user attributes will depend upon your directory server schema. For connection with IBM Tivoli Directory Server (TDS)/ LDAP visit: http://usmanali112.blogspot.com/2012/07/java-authentication-and-connection-with.html


import javax.naming.NamingEnumeration;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.directory.*;

//this class perform all LDAP actions for the user
public class LDAPService {

private String base = "c=us"; // base for LDAP
private String realm = "cn=realm1"; // LDAP realm for user
   
         public void getUserInfo(String name) {
String dn = "sn=" + name + "," + realm + "," + base;

try {
// Initialize LDAP Context
InitialLdapContext context = LDAPConnection.InitializeContext();
String[] att = { "givenName", "mail" };

// Set up Search Controls
SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
sc.setReturningAttributes(att);

// perform search on directory
NamingEnumeration results = context.search(base,
"(objectclass=inetorgperson)", sc);

while (results.hasMore()) {
SearchResult sr = (SearchResult) results.next();

// get the attributes and attribute list
Attributes atts = sr.getAttributes();
NamingEnumeration attrList = atts.getAll();
if (dn.equals(sr.getName() + "," + base)) {
// while we have attributes
while (attrList.hasMore()) {
Attribute attr = (Attribute) attrList.next();
NamingEnumeration values = attr.getAll();
String id, value = "";
while (values.hasMore()) {
id = attr.getID();
value = values.next().toString();
System.out.println(id + " " + value);
}
}
}
}

// Close LDAP Context
LDAPConnection.CloseContext();

} catch (Exception ex) {
ex.getMessage();
}
}
}

Java: Add User in IBM Tivoli Directory Server (TDS) LDAP using JNDI

It will help you to add user or other entries in IBM Tivoli Directory Server (TDS) using JNDI. I used default values and my own user information, so you have to change it according your requirements. Also the user attributes will depend upon your directory server schema. For connection with  IBM Tivoli Directory Server (TDS)/ LDAP visit: http://usmanali112.blogspot.com/2012/07/java-authentication-and-connection-with.html



import javax.naming.ldap.InitialLdapContext;
import javax.naming.directory.*;

//this class perform all LDAP actions for the user
public class LDAPService {

private String base = "c=us"; // base for LDAP
private String realm = "cn=realm1"; // LDAP realm for user

// User information
private String surname = "Ali"; // user surname
private String givenname = "Usman"; // user given name or first name
private String userpassword = "********"; // user password
private String email = "usmanalibutt9393@gmail.com"; // user email
private String distinguish_name = "sn=" + surname + "," + realm + "," + base;

// to add user in LDAP (TDS)
public void addUser() {
try {
InitialLdapContext context = LDAPConnection.InitializeContext();

Attributes attributes = new BasicAttributes();
Attribute objectClass = new BasicAttribute("objectClass");
objectClass.add("inetOrgPerson");
attributes.put(objectClass);

// Define User attributes
attributes.put("sn", surname);
attributes.put("givenName", givenname);
attributes.put("userPassword", userpassword);
attributes.put("mail", email);

// call API to add user
context.createSubcontext(distinguish_name, attributes);

// Close LDAP Context
LDAPConnection.CloseContext();

} catch (Exception ex) {
ex.getMessage();
}
}
}

Java: Authentication and Connection with LDAP using JNDI


This will help you to connect with LDAP using JNDI (Java Naming and Directory Interface). I used this to connect with IBM Tivoli Directory Server (TDS). The connection with LDAP will be on SSL and you can modify it for non SSL too. You can also authenticate a user of IBM Tivoli Directory Server (TDS). If user exists then he will be authenticated otherwise the given authentication method will throw an exception. I have used all default values for the connection, you should change all values according your environment settings.


import java.util.HashMap;
import java.util.Hashtable;
import javax.naming.ldap.InitialLdapContext;

// this class is for LDAP Connection
public class LDAPConnection {
// Set up values for LDAP Context Initialization
private static InitialLdapContext ctx = null;
private static Hashtable<String, String> hashtable = null;

// Set up default parameters for LDAP connection
private static String urlparam = "java.naming.provider.url";
private static String usernameparam = "java.naming.security.principal";
private static String passwordparam = "java.naming.security.credentials";
private static String versionparam = "java.naming.ldap.version";
private static String factory_initialparam = "java.naming.factory.initial";
private static String authenticationparam = "java.naming.security.authentication";
private static String protocolparam = "java.naming.security.protocol";
private static String referralparam = "java.naming.referral";

// Set up default values for LDAP connection
private static String url = "ldap://tameb:636";   // for non SSL use port '389'
private static String username = "cn=root";
private static String password = "object00";
private static String version = "3";
private static String factory_initial = "com.sun.jndi.ldap.LdapCtxFactory";
private static String authentication = "simple";
private static String protocol = "ssl";
private static String referral = "follow";

public static String base = "c=us";
public static String realm = "cn=realm1";

// Provide java trust store parameters where LDAP certificates are imported (in case of  SSL)
private static String truststoreparam = "javax.net.ssl.trustStore";
private static String ts_passwordparam = "javax.net.ssl.trustStorePassword";

// Provide java trust store values where LDAP certificates are imported (in case of  SSL)
private static String truststore = "/usr/java/jre1.6.0_30/lib/security/cacerts";
private static String ts_password = "changeit";

// set connection to LDAP
private static void setConnection() {
try {

// Set up LDAP configuration settings
hashtable = new Hashtable<String, String>();

System.setProperty(truststoreparam, truststore);
System.setProperty(ts_passwordparam, ts_password);

hashtable.put(versionparam, version);
hashtable.put(factory_initialparam, factory_initial);
hashtable.put(authenticationparam, authentication);
hashtable.put(protocolparam, protocol);
hashtable.put(usernameparam, username);
hashtable.put(passwordparam, password);
hashtable.put(referralparam, referral);
hashtable.put(urlparam, url);

// Make LDAP connection
ctx = new InitialLdapContext(hashtable, null);
} catch (Exception ex) {
ex.getMessage();
}
}

// initialize and give LDAP connection context
public static InitialLdapContext InitializeContext() {
setConnection();
return ctx;
}

// close LDAP connection context
public static void CloseContext() {
try {
// Close the connection to LDAP
ctx.close();
} catch (Exception ex) {
ex.getMessage();
}
}

// authenticate LDAP user
public static boolean authenticateUser(String name, String password) {
boolean authenticate = false;
try {

// Set up LDAP configuration settings
hashtable = new Hashtable<String, String>();

System.setProperty(truststoreparam, truststore);
System.setProperty(ts_passwordparam, ts_password);
String username = "sn=" + name + "," + realm + "," + base;
hashtable.put(versionparam, version);
hashtable.put(factory_initialparam, factory_initial);
hashtable.put(authenticationparam, authentication);
hashtable.put(protocolparam, protocol);
hashtable.put(usernameparam, username);
hashtable.put(passwordparam, password);
hashtable.put(referralparam, referral);
hashtable.put(urlparam, url);

// Make LDAP connection
ctx = new InitialLdapContext(hashtable, null);
authenticate = true;

} catch (Exception ex) {
ex.getMessage();
}
return authenticate;
}
}

Tuesday, July 24, 2012

Java: Apache Log4j

This will help you to make logs of your programs. Please include log4j.jar to run this code. you can download this from following link: http://logging.apache.org/log4j/1.2/download.html


// The logger class
import java.io.IOException;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.FileAppender;

public class ServiceLog {

private static Logger logger = null;
private static String pattern = "";
private static String logfile = "ServiceLogInformation";

public static void setLog(Logger loging) {

logger = loging;
pattern += "Milliseconds since program start: %r %n";
pattern += "Classname of caller: %C %n";
pattern += "Date in ISO8601 format: %d{ISO8601} %n";
pattern += "Location of log event: %l %n";
pattern += "Message: %m %n %n";

PatternLayout layout = new PatternLayout(pattern);
FileAppender appender = null;
try {
appender = new FileAppender(layout, logfile, true);
} catch (IOException e) {
e.printStackTrace();
}

logger.addAppender(appender);
}
}

// This class will use above class for logging
import org.apache.log4j.Logger;

public class Service {
     
       private static Logger logger = Logger.getLogger(Service.class);

public static void main(String[] args) {

try {
                           // do something
                 }
                  catch (Exception ex) {
                               ServiceLog.setLog(logger);
                               logger.setLevel((Level) Level.ERROR);
                               logger.error(ex.getMessage());
                   }
}
}

Monday, July 23, 2012

Linux: Configure Samba Server on Ubuntu


This will describe the configuration of Samba Server on Ubuntu. It will help you to access Ubuntu files in Windows and vice versa.

First install samba server in Ubuntu using command line or Ubuntu software center
        $sudo apt-get install samba samba-common
We can check its configuration information using
        $gedit /etc/samba/smb.conf
        or
        $cat /etc/samba/smb.conf

To install graphical interface for samba server configuration use this command
        $sudo apt-get install  system-config-samba


Now share files using this samba server configuration graphical interface. Set the basic options


Set the access to files


The list of directories shared using samba server





Get the ipv4 address of Ubuntu virtual machine.
Note:  If you are using virtual box then in network settings of virtual machine use the ‘host only adapter’ option.


? Write the Ipv4 address in the address bar in windows explorer. Enter username and password of     windows and then windows explorer will show the shared files of Ubuntu virtual machine.
Note: Turn off windows7 firewall for network to avoid any inconvenience. 
Here the ‘_i’ directory of Ubuntu is shared directly using the sharing options of the directory.



Choose any of the shared directories to open.


Samba Client on Windows
Share any directory of windows using advanced sharing option.


In Ubuntu, go to the ‘Network’ directory. Here win-7-pc is the Windows shared place. Double click on it. 
Note: For first time you have to enter username and password of the Windows to enter in it.


Here is the recently shared directory ‘Abstract’. Double click on it.


Enter username and password of the Windows and domain will be ‘WORKGROUP’ and press ‘connect’. 


Here are the files in the shared directory.


Another example of accessing Ubuntu documents in Windows.


Another example of accessing Windows7 documents in Ubuntu.


References:



Linux: Bash Shell Scripting

It will help you to understand Linux bash shell scripting.

Factorial Program
Save this program in a file and it should be an executable file. Run it from terminal like ./file_name


#!/bin/bash
echo -n "enter the number to calculate factorial:"
read number

input=$number;
fact=1;

if [ "$input" -eq "0" ]
then
echo -n "factorial of $input is $fact"
exit 1
else
while [ "$input" -ge "1" ]
do
let "fact =$input * $fact"

input=$((input-1))
done
fi
echo -n "factorial of $number is $fact"

Array Program

Save this program in a file and it should be an executable file. Run it from terminal like ./file_name

#!/bin/bash
echo "enter length of array"
read len1;
declare -a arr;
declare -a arr2;
i=0;
while(("$i" < "$len1"))
do
read num1;
arr[$i]=$num1;
i=$((i+1));
done

echo "2nd array"
j=0;
while(("$j" < "$len1"))
do
read num;
arr2[$j]=$num;
j=$((j+1));
done

echo "Arrays multiplication result is "
k=0;

while(("$k" < "$len1"))
do
 let "res = ${arr[$k]} * ${arr2[$k]}"
 k=$((k+1));
 echo "$res"
done

Linux: Process Management Commands

This lab will help you to learn commands for process management.


•   Start a foreground process, move it to the background and kill it using PID.
Ans. Lets suppose we have 2 files opened in gedit
        $fg %2
        $bg %1
        $kill process_id(1793 etc.)

•   List  all  the  current  running  processes  owned  by  the  current  user  in  user  oriented format.
Ans. $ps -u user_name

•   List only running processes in tree mode.
Ans. $pstree -u user_name

•   Run  a  background  process  from  your  shell  that  finds  a  file  named  cpuinfo,  with lowest possible priority.
Ans. $nice 20 | find /* -name "cpuinfo"&

•   List  priority  value  of  all  running  processes  in  your  system.  Now  reduce  the  priority value of any running process by 5. Compare the new and the old priority values.
Ans. $renice -5 -p process_id(1793 etc.)

Linux: User/Group Management Commands

This lab will help you to learn commands for user and group management


•   See the /etc/passwd and /etc/shadow files
Ans. $cat /etc/passwd
        $cat /etc/shadow

•   Make a new user “tux” with default home directory and password “pakistan”
Ans. $adduser tux
        Enter new UNIX password: pakistan

•   See the changes in /etc/passwd and /etc/shadow
Ans. $cat /etc/passwd
        $cat /etc/shadow

•   Create a group “BIT10” with group ID 99 and change tux’s group to “BIT10”
Ans. $groupadd -g 99 BIT10
        $usermod -a -G BIT10 tux

•   Move the user’s current home directory to the new directory “/studentHome”
Ans. $usermod -d /studentHome tux

•   Change this user’s password to “d!g!t@l” with following settings:-
•   Lock the account if it has been inactive for 5 days
•   Minimum 2 days must be past before the user can change hi/her/its password
Ans. $passwd
        d!g!t@l
        $passwd -l tux

        $passwd -n 2 tux
        $passwd -i 5 tux
        or
        $chage tux (It is used to manually enter the values for (minimum,inactive))
        To view information
        $chage -l tux

•   See the changes in /etc/passwd and /etc/shadow and /etc/group files
Ans. $cat /etc/passwd
        $cat /etc/shadow

•   Delete the group “BIT10” and delete the account of “tux”
Ans. $userdel tux
        $groupdel BIT10

Linux: AWK Script (Pattern Processing Language)

This will give you little idea about AWK Script


1.  Write an AWK program that numbers each line in a file and sends its output to standard output.
Ans. gawk ‘{print NR, $0}’


2.  Write an AWK program that displays the number of characters in the first field followed by the first
field and sends its output to standard output.
Ans. gawk ‘{print length($1), $1}’


3.  Use AWK to determine how many lines in /usr/share/dict/words contain the string abul. Verify your
answer using grep.
Ans. BEGIN { total =0}
        /abul/ {total ++}
        END {print total}


4.  Using AWK, count the number of lines in a file.
Ans. BEGIN { total =0}
        {total ++}
        END {print total}
        or
        END {print NR}




Linux: Managing file permissions/ownership, set up ACLs, hard and soft links Commands

This lab will be very helpful to understand the commands for managing file permissions and ownership, set up ACLs, hard and soft links.



Managing File Permissions and Ownership
•   List files in /sbin directory
Ans. $ ls -l /usr/sbin

•   Create a file and change its permissions so that owner can only read the file and the respective group can read/write the file while other can read/write/execute the file using octal values
Ans. $ chmod 467 file_name

•   Change the permissions of the file so that user can read/write/execute the file, group can read/execute the file and others can only read the file without using octal values
Ans. $ chmod u=rwx,g=rx,o=r file_name

•   Create a new user “Lab_user” and change the ownership of the file to this new user
Ans. $ sudo useradd lab_user
     $ sudo chown lab_user file_name

•   Create a new group “Lab_users” and assign this group to the file
Ans. $ sudo groupadd lab_users
     $ sudo chgrp lab_users file_name

•   Change the default permissions to rwx rw- r--
Ans. $ umask 013

•   Create directory so that only the owner or root can delete the directory
Ans. $ mkdir test
     $ chmod o+t test or or $ chmod 100 test

•   Create a file so that when it is executed, the group ID of the process is changed to the group ID of the file
Ans. $ mkdir directory_name
     $ sudo chown lab_user directory_name

Set up ACLs
•   As root, create a dir ‘acl_test’ in /tmp and set its permission as 700
Ans. $ sudo mkdir /tmp/acl_test
     $ sudo chmod 700 /tmp/acl_test
 
•   As username, try to change into this dir
Ans.  "you do not have permissions necessary to open the file"  

•   Using ACL, allow username to change into this dir
Ans. $ setfacl -m u:username:rwx /tmp/acl_test

•   As root, create a file in this dir
Ans. $ touch /tmp/acl_test/test_acl_file

•   Change default ACL of this dir, giving username rw- access
Ans. $ setfacl -d -m u:username:rw_ /tmp/acl_test

•   Create another file in the same dir
Ans. $ touch /tmp/acl_test/test_acl_file2

•   Compare the two files ACLs using getfacl
Ans. $ getfacl /tmp/acl_test/test_acl_file, getfacl /tmp/acl_test/test_acl_file2

•   Remove ACLs from this directory completely
Ans. $ setfacl -x u:username /tmp/acl_test

Hard and Soft Links
•   Go into the tmp directory
Ans. $ cd tmp

•   Make a directory called original
Ans. $ mkdir original

•   Copy the /etc/host.conf file or any file to test with here
Ans. $ cp /etc/host.conf /tmp/original

•   List the contents and take note of the inode (first column)
Ans. $ cat original/host.conf
     $ ls -i original/host.conf  or stat original/host.conf

•   Create a symbolic link to host.conf called linkhost.conf
Ans. $ ln -s host.conf linkhost.conf

•   Now list out the inodes again
Ans. $ ls -i

•   Notice if the the inode for the link is different?
Ans. Yes, inode for the softlink is different.

•   Now create a hard link to the same file called hardhost.conf
Ans. $ ln host.conf hardhost.conf

•   Now list the inodes one more time
Ans. $ ls -i

•   Notice if the the inode for the link is different?
Ans. No. inode for the hardlink is same as of the file inode.

•   Open up linkhost.conf and edit it and save it
Ans. $ gedit linkhost.conf

•   Now look in host.conf and notice if the changes were made
Ans. Yes, changes are made in both host.conf and linkhost.conf.

•   Lets cut/paste host.conf up one directory and see if it causes any problems
Ans. Yes, it causes problems. 'linkhost.conf' becomes invalid. 'hardhost.conf' is valid.

•   Do ls and see what is the result?
Ans. Now using ls command. linkhost.conf is displayed in red. hardhost.conf is  displayed blue.

•   What is the result of cat linkhost.conf?
Ans. $ cat linkhost.conf
     Result: -           cat: linkhost.conf: No such file or directory

•   What is the result of cat hardhost.conf?
Ans. $ cat hardhost.conf
     Result: -          Whole file content is shown








Linux: Commands (find, which, type, grep/egrep)

This will help you to understand Linux commands like find, which, type, grep/egrep

find:
•   Find all lib files greater than 100 KB in /lib
Ans. $ find /lib -size +100k

•   Find all files which are smaller than 200 bytes
Ans. $ find /lib -size -200c

•   Find all symbolic links in /lib
Ans. $ find /lib -type l

•   Find all files which have been modified in last 24 hours
Ans. $ find /lib -mtime -1

•   Find the file “cpuinfo” and print its first lines using “head” in the same command
Ans. $ head `find / -name "cpuinfo"`

•   Find your group name and ID, and search all files which belong to your group using group name and ID
Ans. groupname: $ whoami
        groupid:   $ id-g
        $ find -group root
        $ find -gid 0

•   Find all files which have “.so” in their names using regular expressions
Ans. $ find -name "*.so"

which:
•   Find paths of “find”, “cd”, “ifconfig” and “cp”
Ans. $ which find
        $ which cd
        $ which ifconfig
        $ which cp

•   Find all paths for “java” and “g++”
Ans. $ which -a java
        $ which -a g++

type:
•   Find type of “man”
Ans. $ type man

•   Find all types of “java” and “g++”
Ans. $ type -a java
        $ type -a g++

grep/egrep:
•   Find the files containing string “/proc” in /etc
Ans. $ grep -lr "/proc" /etc

•   Find the files in /etc which contains the string “nameserver” at start of a line
Ans. $ egrep -lr "^nameserver" /etc

•   Find the files which contain the words “ext2” or “ext3” or “reiser”
Ans. $ egrep -lr "(ext2|ext3|reiser)" /

•   Find the files starting with the letter ‘m’ and containing string “MemFree” in /proc
Ans. $ grep "MemFree" `find /usr/bin -name "m*"`

•   Find all the files which contains “i586” in /etc and /home
Ans. $ grep -lr "i586" /etc /home



Linux: Basic Commands

This will help you to understand the basic commands for Linux


1.     Show the present working directory
Ans. pwd shows the current working directory and stands for "print working directory".
        usman@ubuntu:~$ pwd

2.     Show the current user's session information in long format
Ans. usman@ubuntu:~$ finger -l

3.     Show the current user's group membership
Ans. usman@ubuntu:~$ groups usman              // 'usman' is the current user

4.     Show the current user's PATH
Ans. usman@ubuntu:~$ echo $path

5.     Make a directory in the current user's home directory called lab2
Ans. usman@ubuntu:~$ mkdir lab2       // your current directory should be user's home directory

6.     Make two files in the lab2 directory: test and .test
Ans. usman@ubuntu:~$ touch lab2/test
        usman@ubuntu:~$ touch lab2/.test

7.     Make a directory in the lab2 directory named sub1
Ans. usman@ubuntu:~$ mkdir lab2/sub1

8.     Use head to show the first line in 'test'
Ans. usman@ubuntu:~$ head -1 lab2/test

9.     Use tail to show the last line in 'test'
Ans. usman@ubuntu:~$ tail -1 lab2/test

10.   Use cat to show the contents of test
Ans. usman@ubuntu:~$ cat -A lab2/test

11.   Change to the current user's home directory
Ans. usman@ubuntu:~$ cd

12.   Use ls to recursively list the lab2 directory
Ans. usman@ubuntu:~$ ls -R lab2

13.   Use rmdir to delete the sub1 directory
Ans. usman@ubuntu:~$ rmdir lab2/sub1

14.   Use rm to delete the lab2 directory recursively
Ans. usman@ubuntu:~$ rm -R lab2

C#: Send Email

This program will send email using gmail smtp client


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;

namespace TestEmail
{
    public class Email
    {
private void sendMail()
        {
            string from         = "abc@gmail.com";
    string password = "******";
    string to             = "xyz@gmail.com";
    string subject     = "Subject Text";
    string body        = "Body Text";

            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
            mail.To.Add(to);
            mail.From = new MailAddress(from, "Name" , System.Text.Encoding.UTF8);
            mail.Subject = subject;
            mail.SubjectEncoding = System.Text.Encoding.UTF8;
            mail.Body = body;
            mail.BodyEncoding = System.Text.Encoding.UTF8;
            mail.IsBodyHtml = true ;
            mail.Priority = MailPriority.High;
            password = password;
            SmtpClient client = new SmtpClient();

            //Add the Creddentials- use your own email id and password

            client.Credentials = new System.Net.NetworkCredential(from, password);

            client.Port = 587; // Gmail works on this port
            client.Host = "smtp.gmail.com";
            client.EnableSsl = true; //Gmail works on Server Secured Layer
client.Send(mail);
        }
    }
}