Skip to main content

Posts

Showing posts from November, 2013

LINUX How to Install Ruby and make it executable as a CGI

1 Install Ruby [root@www ~]#yum -y install ruby [root@www ~]#vi /etc/httpd/conf/httpd.conf # line 796: add extension for ruby script AddHandler cgi-script .cgi .pl .rb [root@www ~]#/etc/rc.d/init.d/httpd restart Stopping httpd:[ OK ] Starting httpd:[ OK ] 2 Create a test script and make sure if it works [root@www ~]#vi /var/www/html/index.rb #!/usr/bin/ruby print "Content-type: text/html\n\n" print "<html>\n<body>\n" print "<div style=\"width: 100%; font-size: 40px; font-weight: bold; text-align: center;\">\n" print "Ruby Test Page<br />" print Time.now.strftime('%Y/%m/%d') print "\n</div>\n" print "</body>\n</html>\n" [root@www ~]#chmod 705 /var/www/html/index.rb  

LINUX How to using perl script

1 Enable CGI executing and use perl script. [root@www ~]#yum -y install perl perl-CGI  2 Configure httpd. [root@www ~]#vi /etc/httpd/conf/httpd.conf # line 331: change (enable CGI and disable Indexes)  Options FollowSymLinks ExecCGI # line 402: add file name that it can access only with directory's name DirectoryIndex index.html index.cgi # line 796: uncomment and add file-type that apache looks them CGI AddHandler cgi-script .cgi .pl [root@www ~]#/etc/rc.d/init.d/httpd restart Stopping httpd:[ OK ] Starting httpd:[ OK ] 3 Create a CGI test page and access to it with web browser. It's OK if following page is shown. [root@www ~]#vi /var/www/html/index.cgi #!/usr/bin/perl print "Content-type: text/html\n\n"; print "<html>\n<body>\n"; print "<div style=\"width: 100%; font-size: 40px; font-weight: bold; text-align: center;\">\n"; print "CGI Test Page"; print "\n</div>\n"; print "</body&g

LINUX How to Install PHP to use it

1 Install PHP to use it. [root@www ~]#yum -y install php php-mbstring php-pear [root@www ~]#vi /etc/httpd/conf/httpd.conf # line 402: add file name that it can access only with directory's name DirectoryIndex index.html index.php [root@www ~]#vi /etc/php.ini # line 946: set your timezone date.timezone ="Asia/Tokyo" [root@www ~]#/etc/rc.d/init.d/httpd restart Stopping httpd:[ OK ] Starting httpd:[ OK ] 2 Create a PHP test page and access to it with web browser. It's OK if following page is shown [root@www ~]#vi /var/www/html/index.php <html> <body> <div style="width: 100%; font-size: 40px; font-weight: bold; text-align: center;"> <?php print Date("Y/m/d"); ?> </div> </body> </html>  Open browser with address http://my-server.com/index.php

LINUX How to use crontab

Crontab The crontab (cron derives from chronos , Greek for time; tab stands for table ) command, found in Unix and Unix-like operating systems, is used to schedule commands to be executed periodically. To see what crontabs are currently running on your system, you can open a terminal and run: sudo crontab -l To edit the list of cronjobs you can run: sudo crontab -e This wil open a the default editor (could be vi or pico, if you want you can change the default editor) to let us manipulate the crontab. If you save and exit the editor, all your cronjobs are saved into crontab. Cronjobs are written in the following format:    * * * * * /bin/execute/this/script.sh  Scheduling explained As you can see there are 5 stars. The stars represent different date parts in the following order: minute (from 0 to 59) hour (from 0 to 23) day of month (from 1 to 31) month (from 1 to 12) day of week (from 0 to 6) (0=Sunday) Execute every minute If you leave the star, or asterisk, it means every . Maybe th

LINUX Add repository for yum

1 Add RPMforge Repository for yum because that has many useful packages. [root@dlp ~]#wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm [root@dlp ~]#rpm -Uvh rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm Preparing... ###################################### [100%] 1:rpmforge-release ###################################### [100%] [root@dlp ~]#sed -i -e "s/enabled = 1/enabled = 0/g" /etc/yum.repos.d/rpmforge.repo # when you use the repository, input yum command like follows [root@dlp ~]# yum --enablerepo=rpmforge install  2 Add repository EPEL that is provided from Fedora project. [root@dlp ~]#wget http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm [root@dlp ~]#rpm -Uvh epel-release-6-8.noarch.rpm Preparing... ###################################### [100%] 1:epel-release ###################################### [100%] [root@dlp ~]#sed -i -e "s/enabled=1/enabled=0/g

LINUX Install phpmyadmin to operate MySQL from Web browser

[root@www ~]#yum --enablerepo=epel -y install phpMyAdmin php-mysql php-mcrypt   # install from EPEL [root@www ~]#vi /etc/httpd/conf.d/phpMyAdmin.conf # line 14: add IP address you permit Allow from 127.0.0.1 10.0.0.0/24 [root@www ~]#/etc/rc.d/init.d/httpd reload Reloading httpd:     [  OK  ] Access to 'http://(your hostname or IP address)/(alias name you set)/' with web browser, then following screen is shown. Login with a user in MySQL. 

LINUX Install Samba and Create a shared directory

Install Samba and Create a shared directory that anybody can read and write, and authentication is not needed. [root@lan ~]#yum -y install samba [root@lan ~]#mkdir /home/share [root@lan ~]#chmod 777 /home/share [root@lan ~]#vi /etc/samba/smb.conf # near line 58: add unix charset = UTF-8 dos charset = CP932 # line 75: change (Windows' default) workgroup =WORKGROUP # line 81: uncomment and change IP address you allow hosts allow = 127.10.0.0. # line 102: change (no auth) security =share # add at the bottom [Share]                                           # any name you like    path = /home/share                     # shared directory    writable = yes                             # writable    guest ok = yes                             # guest OK    guest only = yes                          # guest only    create mode = 0777                    # fully accessed    directory mode = 0777               # fully accessed    share modes = yes                       # warn if some people acc

LINUX How to Install and Configure Subversion with Apache

Install and Configure Subversion.  [root@www ~]#yum -y install subversion mod_dav_svn [root@www ~]#vi /etc/httpd/conf.d/subversion.conf # line 26-40: uncomment and change like follows <Location /repos>    DAV svn    SVNParentPath /var/www/svn # # Limit write permission to list of valid users.    <LimitExcept GET PROPFIND OPTIONS REPORT>       # Require SSL connection for password protection.       SSLRequireSSL       AuthType Basic       AuthName "Authorization Realm"       AuthUserFile /etc/httpd/conf/.htpasswd           # specify access control file      AuthzSVNAccessFile /etc/svnusers       Require valid-user    </LimitExcept> </Location> [root@www ~]# vi /etc/svnusers # set access right like an example below [site:/] # all users are writable * = rw # cent is writable [site:/directory] cent = rw # userB is readable userB = r # userC is not permitted userC = [root@www ~]# mkdir -p /var/www/svn/site [root@www ~]#svnadmin create /var/www/svn/site # cr

LINUX Install VNC Server to operate Server with GUI remotely from Windows client.

LINUX Install VNC Server [root@dlp ~]# yum -y install tigervnc-server [root@dlp ~]# su - cent # switch to a user you'd like to config VNC [cent@dlp ~]$ vncpasswd # set VNC password Password:     # input Verify:          # confirm [cent@dlp ~]$ vncserver :1 # start xauth: creating new authority file /home/cent/.Xauthority New 'dlp.server.world:1 (cent)' desktop is dlp.server.world:1 Creating default startup script /home/cent/.vnc/xstartup Starting applications specified in /home/cent/.vnc/xstartup Log file is /home/cent/.vnc/dlp.server.world:1.log [cent@dlp ~]$ vncserver -kill :1 # stop Killing Xvnc process ID 2187 [cent@dlp ~]$ vi /home/cent/.vnc/xstartup # twm & # last line: make it comment exec gnome-session & # run Ghome # run with diplay number '1', screen resolution '800x600', color depth '24' [cent@dlp ~]$ vncserver :1 -geometry 800x600 -depth 24

LINUX Password authentication

Configure SSH server for Windows clietnts' computer to be able to login from them. This is the way with Password Authentication. [root@dlp ~]#vi /etc/ssh/sshd_config # line 42: uncomment and change 'no' PermitRootLogin no # line 65: uncomment PermitEmptyPasswords no PasswordAuthentication yes [root@dlp ~]#/etc/rc.d/init.d/sshd restart Stopping sshd:[  OK  ] Starting sshd:[  OK  ]

LINUX How to create an admin user

1 Create an admin user.  [root@dlp ~]#useradd cent [root@dlp ~]#passwd cent Changing password for user cent. New UNIX password: # set password Retype new UNIX password: # Confirm passwd: all authentication tokens updated successfully. [root@dlp ~]#exit # logout 2 Try to switch to a user that was added above dlp login:cent # input user name password: # password [cent@dlp ~]$su - # switch to root Password: # root password [root@dlp ~]# # just switched to root 3 Make a user (it's 'cent' in this example) be only a user who can switch to root    as an administration user.  [root@dlp ~]#usermod -G wheel cent [root@dlp ~]#vi /etc/pam.d/su #%PAM-1.0 auth sufficient pam_rootok.so # Uncomment the following line to implicitly trust users in the "wheel" group. #auth sufficient pam_wheel.so trust use_uid # Uncomment the following line to require a user to be in the "wheel" group. # uncomment the following line auth required pam_wheel.so use_uid auth include system-

LINUX How to make ssh key

Generating SSH Keys Step 1: Check for SSH keys First, we need to check for existing ssh keys on your computer. Open up Terminal and run: cd ~/.ssh ls # Lists the files in your .ssh directory   Check the directory listing to see if you have a file named  either id_rsa.pub or id_dsa.pub . If you don't have either of those files go to step 2 . Otherwise, you already have an existing keypair, and you can skip to step 3 . Step 2: Generate a new SSH key To generate a new SSH key, enter the code below. We want the default settings so when asked to enter a file in which to save the key, just press enter. ssh-keygen -t rsa -C " your_email@example.com " # Creates a new ssh key, using the provided email as a label # Generating public/private rsa key pair. # Enter file in which to save the key (/Users/ you /.ssh/id_rsa): [Press enter] ssh-add id_rsa Now you need to enter a passphrase. Enter passphrase (empty for no passphrase): [Type a passphrase] # Enter same passphrase a

LINUX How to Control System Processes via SSH

The hearth of each OS are its (apart from the Kernel of course) processes. Linux provides various ways to control the current running processes on the server and we will list a couple of examples to illustrate them. Probably the command you would most often use is the “ ps ” command which lists all processes based on a certain criteria. Please note that you can not manipulate the system processes (executing ps, kill, pgrep, top and strace) on the shared server, since your account will not have such privileges. However, on our dedicated servers you will have root permissions and you will be able to control the system processes. To list all processes which are started by your user, you can use: ps x where ps is naturally the command itself and x is the argument we are passing to it. The result will look like the following one: PID TTY STAT TIME COMMAND 3735 pts/0 R 0:00 bash 3775 pts/0 R+ 0:00 ps x 5032 ? Ss 1:01 wget -mbr --no-passive-ftp…. There are 5 columns in the result, eac

LINUX Managing file/folder permissions and ownership

The Unix files access is controlled. There are three types of access (permissions): read write execute Each file belongs to a specific user and group (ownership). Access to the files is controlled by user, group, and what is called other/everyone permission bits and is usually set using a numerical value. For example, 644 as permission bit will result in: Owner / User Group Other/ Everyone 644 Each number represents the access level and it can be from 0 to 7. The access level, depending on the number is as follows: 0 - no access to the file whatsoever 1 - execute permissions only 2 - write permissions only 3 - write and execute permissions 4 - read permissions only 5 - read and execute permissions 6 - read and write permissions 7 - read, write and execute permissions (full permissions) Thus the above 644 permissions example will look like this: Owner / User - Read and Write Group - Read and Write Other/ Everyone - Read only To allow a script to be executed and read by everyone but

LINUX Move and copy files using SSH

Often you will need to move one or more files/folders or copy them to a different location. You can do so easily using an SSH connection. The commands which you would need to use are mv (short from move) and cp (short from copy). The mv command syntax looks like this: mv configuration.php-dist configuration.php By issuing the above command we will move (rename) the file configuration.php-dist to configuration.php. You can also use mv to move a whole directory and its content: mv includes/* ./ This will move all files (and folders) in the includes/ directory to the current working directory. In some cases however, we will need to only update the files and move only files that were changed, which we can do by passing ‘ -u ’ as argument to the command: mv -u includes/* admin/includes The copy (cp) command works the same way as mv, but instead of moving the files/folders it copies them. For example: cp configuration.php-dist configuration.php The command will copy the configuration

LINUX How to Search for Files and Folders via SSH

In some cases you would need to find the location of a given file or to search for a certain text in all files under a directory. SSH provides two different commands, which can be used to accomplish this. In order to search for a file location you can use the find command. Find is a very powerful tool and accepts various arguments allowing you to specify the exact search term (i.e search by name, by type or even by modified time). For example, to search for a file called myFile.txt under the current folder (and all subfolders), you would need to use the following command: find . -name myFile.txt If you are uncertain about the file name or would like to match a part of the name, you can use a wildcard pattern: find . -name “myFile*” If you would like to list only directories and leave all files out of the result: find . -type d Or if you want to filter only files modified for the last 2 days, you would need to use: find . -mtime -2 You can also search for a given text in the fi

LINUX List files and directories using SSH

In order to list all files and directories using an SSH client, you would need to execute the appropriate command. The command name, in this case, is ls and it accepts various parameters. When using the command alone (without arguments): ls the output will be all visible files and folders without additional formatting or information. In order to view more information about the files (such as their permissions, ownership, last modified date, etc) and at the same time to list the files and directories, you would need to supply additional arguments to the command. The most common arguments are as follows: ls –a(Short from –all) Lists all files and folders including hidden (starting with a dot) files and directories. ls –R (Short from –Recursive) Lists recursively (i.e follows subfolders as well) all files and folders under the current directory. ls -l (Short from –long) Lists all files and folders, each on a separate line, and provides additional information about them (permission

LINUX How to Delete Files and Folders via SSH

Sometimes you would need to remove a file or a folder from the system. To do so using SSH, you would need to execute the appropriate command – rm. The command in its simpliest form looks like: rm myFile.txt myFile1.txt myFile2.txt …etc… You would notice however that listing all files/folders that need to be deleted can be quite time consuming. Fortunately, rm accepts several arguments which can ease us. In the above example, we could type: rm myFile*.txt This will match all files starting with ‘myFile’ and ending in ‘.txt’ To delete a whole folder and its content recursively, you can use: rm -rf foldername/ To delete all files/folders in the current directory, without deleting the directory itself, you would need to use: rm -rf * Please be very careful when using rm command, as it might have devastating effects on your website/server, should you delete a system file or a folder.

LINUX how to use ssh to run shell script on a remote machine

If Machine A is a Windows box, you can use Plink (part of PuTTY ) with the -m parameter, and it will execute the local script on the remote server. plink root@MachineB - m local_script . sh If Machine A is a Unix-based system, you can use: ssh root@MachineB 'bash -s' < local_script . sh You shouldn't have to copy the script to the remote server to run it.

LINUX How to use secure copy (scp)

Copy the file "foobar.txt" from a remote host to the local host $ scp your_username@remotehost.edu:foobar.txt /some/local/directory Copy the file "foobar.txt" from the local host to a remote host $ scp foobar.txt your_username@remotehost.edu:/some/remote/directory Copy the directory "foo" from the local host to a remote host's directory "bar" $ scp -r foo your_username@remotehost.edu:/some/remote/directory/bar Copy the file "foobar.txt" from remote host "rh1.edu" to remote host "rh2.edu" $ scp your_username@rh1.edu:/some/remote/directory/foobar.txt \ your_username@rh2.edu:/some/remote/directory/ Copying the files "foo.txt" and "bar.txt" from the local host to your home directory on the remote host $ scp foo.txt bar.txt your_username@remotehost.edu:~ Copy the file "foobar.txt" from the local host to a remote host using port 2264 $ scp -P 2264 foobar.txt your_username@remotehost.

LINUX How to create an archive using tar

Connect to a shell or open a terminal/console on your Linux/Unix machine. To create an archive of a directory and its contents you would type the following and press enter: tar -cvf name.tar /path/to/directory Substitute the name.tar with the name of the tar file you would like to create and substitute the directory name for the full path to the directory you would like to archive. To create an archive of certfain files you would type the following and press enter: tar -cvf name.tar /path/to/file1 /path/to/file2 /path/to/file3 Substitute the name.tar with the name of the tar file you would like to create and substitute the the various files for the full path to the files you would like to archive. Each file you would like included in the archive should be seperated by a space.

LINUX How to configure VirtualHost

Server configuration vi /etc/httpd/conf/httpd.conf # Ensure that Apache listens on port 80 Listen 80 # Listen for virtual host requests on all IP addresses NameVirtualHost *:80 <VirtualHost *:80> DocumentRoot /www/example1 ServerName www.example.com # Other directives here </VirtualHost> <VirtualHost *:80> DocumentRoot /www/example2 ServerName www.example.org # Other directives here </VirtualHost>

LINUX How to create soft link / symbolic link

To create a symbolic link in Unix or Linux, at the shell prompt, enter the following command: ln -s {target-filename} {symbolic-filename} For example create softlink for /webroot/home/httpd/test.com/index.php as /home/vivek/index.php, enter the following command: ln -s /webroot/home/httpd/test.com/index.php /home/vivek/index.php ls -l Output lrwxrwxrwx 1 vivek vivek 16 2007-09-25 22:53 index.php  -> /webroot/home/httpd/test.com/index.php  

IOS Add Buttons to the Alert

Add Buttons to the Alert UIAlertView *message = [[UIAlertView alloc] initWithTitle: @"Hello World!"                                                    message: @"This is your first UIAlertview message."                                                   delegate: nil                                          cancelButtonTitle: @"Button 1"                                          otherButtonTitles: @"Button 2" , @"Button 3" , nil ]; [message show]; Respond to Alert Button Selection - ( void )alertView:(UIAlertView *)alertView clickedButtonAtIndex:( NSInteger )buttonIndex {      NSString *title = [alertView buttonTitleAtIndex:buttonIndex];      if ([title isEqualToString: @"Button 1" ])      {          NSLog ( @"Button 1 was selected." );      }      else if ([title isEqualToString: @"Button 2" ])      {          NSLog ( @"Button 2 was selected." );      }      else if ([title isEqualToString: @&qu

IOS iPhone/iPad – Get User-Agent for UIWebView

In each new version of iOS the browser gets a new user-agent string. I’ve been searching for a way to get the user-agent string from the API but haven’t been able to find a straight forward way to do it. Here’s my solution: WebViewUserAgent.h #import <Foundation/Foundation.h>   @interface WebViewUserAgent : NSObject <UIWebViewDelegate> { NSString *userAgent; UIWebView *webView; } @property (nonatomic, retain) NSString *userAgent; -(NSString*)userAgentString; @end   WebViewUserAgent .m   #import "WebViewUserAgent.h"     @implementation WebViewUserAgent @synthesize userAgent;   -(NSString*)userAgentString { webView = [[UIWebView alloc] init]; webView.delegate = self; [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString: @"www.google.com"]]];   // Wait for the web view to load our bogus request and give us the 

IOS How to get a UIScrollView scrolling and paging

The secret to understanding the scroll view is that it has a frame size and a content size. You only need to create the frame size big enough to fit the view whereas the content size will be larger in order for it to scroll. Here is code that can be placed in the viewDidLoad of your ViewController.m file, and incorporates paging as well. It assumes that you have already created a UIScrollView in Interface Builder and called it scrollView: // Adjust scroll view content size, set background colour and turn on paging scrollView .contentSize = CGSizeMake(scrollView .frame .size .width * 12 , scrollView .frame .size .height ) ; scrollView .pagingEnabled =YES ; scrollView .backgroundColor = [UIColor blackColor] ; // Generate content for our scroll view using the frame height and width as the reference point int i = 0 ; while (i < 12) { UIView *views = [[UIView alloc] initWithFrame:CGRectMake(((scrollView .frame .size .width )*i)+

IOS How to add a touch event to a UIView

//The setup code (in viewDidLoad in your view controller) UITapGestureRecognizer * singleFingerTap = [[ UITapGestureRecognizer alloc ] initWithTarget : self action : @selector ( handleSingleTap :)]; [ self . view addGestureRecognizer : singleFingerTap ]; [ singleFingerTap release ]; //The event handling method - ( void ) handleSingleTap :( UITapGestureRecognizer *) recognizer { CGPoint location = [ recognizer locationInView :[ recognizer . view superview ]]; //Do stuff here... }

LINUX Viewing text files from the shell prompt

The head Command head <filename> By default, you can only read the first ten lines of a file.You can change the  number of lines displayed by specifying a number option. head -20 <filename> The tail Command   The reverse of head is tail . Using tail , you can view the last ten lines of a file. This can be useful for viewing the last ten lines of a log file for important system messages. You can also use tail to watch log files as they are updated. Using the -f option, tail automatically prints new messages from an open file to the screen in real-time. For example, to actively watch /var/log/messages , enter the folowing at a shell prompt (as the root user):  tail -f /var/log/messages Press [Ctrl] - [C] when you are finished. Viewing Files with less The format of the less command is: less <filename> The main difference between more and less is that less allows backward and single-line movement using the same navigation as man pages: pr

LINUX How to Disabling / Enabling Yum Repository

To add such a repository to your system and enable it, run the following command as root : yum-config-manager --add-repo repository_url Example yum-config-manager --add-repo http://www.example.com/example.repo   To enable a particular repository or repositories,  type the following at a shell prompt as root : yum-config-manager --enable repository … Example yum-config-manager --enable example To disable a Yum repository, run the following command as root : yum-config-manager --disable repository … Example   yum-config-manager --disable example

LINUX How to configure sudoers file

Just edit the file /etc/sudoers # sudoers file. # # This file MUST be edited with the 'visudo' command as root. # # See the sudoers man page for the details on how to write a sudoers file. # # Host alias specification # User alias specification # Cmnd alias specification # Defaults specification # User privilege specification root    ALL=(ALL) ALL userA    ALL=(ALL) ALL userB   ALL=(ALL) ALL # Uncomment to allow people in group wheel to run all commands # %wheel        ALL=(ALL)       ALL # Same thing without a password # %wheel        ALL=(ALL)       NOPASSWD: ALL # Samples # %users  ALL=/sbin/mount /cdrom,/sbin/umount /cdrom # %users  localhost=/sbin/shutdown -h now userC       ALL=NOPASSWD: /usr/sbin/chroot, /bin/su - userC unknown-mail       ALL=NOPASSWD: /bin/chmod -R 777 /usr/local/src/deploy/blog/cache/ unknown-mail       ALL=NOPASSWD: /bin/chmod -R 777 /usr/local/src/deploy/site/cache/

LINUX How to make script backup database

#!/bin/bash # Backup mysql database backuptime=`date "+%F-%H-%M-%S"` # All the databases . mysqldump -h localhost --user remote --password=nopass --default-character-set=cp932 bugtracker > /home/backup/backup/database/mantis.db .$backuptime.sql mysqldump -h localhost --user remote --password=nopass --default-character-set=cp932 testlink > /home/backup/backup/database/testlink.db.$backuptime.sql #End backup db

LINUX How to configure authen basic for folder

Example we set authen basic for WebBase folder 1. cd WebBase 2. In  WebBase folder make .htaccess     vim .htaccess Add contents :     AuthUserFile /var/www/html/private/.htpasswd    AuthGroupFile /dev/null    AuthName "My Private Directory"    AuthType Basic <Limit GET POST> require valid-user </Limit>  3. Make file .htpasswd with username is admin    htpasswd -c /var/www/html/private/.htpasswd admin

LINUX How to using mysqldump

mysqldump writes information as SQL statements to the standard output. You can save the output in a file: shell> mysqldump [ arguments ] > file_name To dump all databases, invoke mysqldump with the --all-databases option: shell> mysqldump -uusername -pxxxxxx --all-databases > dump.sql To dump only specific databases, name them on the command line and use the --databases option: shell> mysqldump -uusername -pxxxxxx --databases db1 db2 db3 > dump.sql

LINUX How to configure ssl-postfix-dovecot

# cd /etc/postfix # vi main.cf Paste under mynetworks: ####### smtp auth smtpd_tls_auth_only = yes smtp_use_tls = yes smtpd_sasl_auth_enable =   yes smtpd_sasl_type = cyrus local_recipient_maps = smtpd_use_tls = yes smtp_tls_note_starttls_offer   = yes smtpd_tls_key_file =   /etc/postfix/ssl/smtpd.key smtpd_tls_cert_file =   /etc/postfix/ssl/smtpd.crt smtpd_tls_CAfile =   /etc/postfix/ssl/cacert.pem smtpd_tls_loglevel = 1 smtpd_tls_received_header   = yes smtpd_tls_session_cache_timeout   = 3600s tls_random_source =   dev:/dev/urandom ######## Then: # vi master.cf Paste under smtp: smtps   inet n   -   n   - - smtpd       -o smtpd_sasl_auth_enable=yes       -o smtpd_reject_unlisted_sender=yes       -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject       -o broken_sasl_auth_clients=yes To check the SASL available mechanisms run: # saslauthd -V Set SASL authentication to start at system boot: # chkconfig --levels 235 saslauthd on Set up the encryption keys: #mkdir /etc/pos

LINUX How to convert image with Imagemagick

Convert ai to pdf,gif,jpg mogrify -crop 2000x2000+190+725 +repage -colorspace RGB -density 300 -format jpg *.ai mogrify -crop 2000x2000+190+725 +repage -colorspace RGB -density 300 -format png *.ai mogrify -crop 2000x2000+190+725 +repage -colorspace RGB -density 300 -format pdf *.ai Convert all *jpg to pdf mogrify -format pdf *.jpg Resize Image mogrify -resize 575x -crop 480x480+45+160 +repage -colorspace RGB -density 300 -format gif *.ai

LINUX Getting the IP Address Using DHCP

Getting the IP Address Using DHCP [root@bigboy tmp]# cd /etc/sysconfig/network-scripts [root@bigboy network-scripts]# vi ifcfg-eth0 # # File: ifcfg-eth0 # DEVICE=eth0 BOOTPROTO=dhcp ONBOOT=yes After configure finished type: [root@bigboy network-scripts]# ifdown eth0 [root@bigboy network-scripts]# ifup eth0 to detect new configure

LINUX How to configure for eth0

root@bigboy tmp]# cd /etc/sysconfig/network-scripts [root@bigboy network-scripts]# vi ifcfg-eth0 # File: ifcfg-eth0 # DEVICE=eth0 # set name device configure IPADDR=192.168.1.100 # ip address NETMASK=255.255.255.0 # subnetmask BOOTPROTO=static #  static ip ONBOOT=yes # active when system start

LINUX How to ssh without pasword

Step 1: Create public and private keys using ssh-key-gen on local-host jsmith@local-host$ [Note: You are on local-host here] jsmith@local-host$ ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/home/jsmith/.ssh/id_rsa):[Enter key] Enter passphrase (empty for no passphrase): [Press enter key] Enter same passphrase again: [Pess enter key] Your identification has been saved in /home/jsmith/.ssh/id_rsa. Your public key has been saved in /home/jsmith/.ssh/id_rsa.pub. The key fingerprint is: 33:b3:fe:af:95:95:18:11:31:d5:de:96:2f:f2:35:f9 jsmith@local-host Step 2: Copy the public key to remote-host using ssh-copy-id jsmith@local-host$ ssh-copy-id -i ~/.ssh/id_rsa.pub remote-host jsmith@remote-host's password: Now try logging into the machine, with "ssh 'remote-host'", and check in: .ssh/authorized_keys to make sure we haven't added extra keys that you weren't expecting. Note: ssh-copy-id appends the keys to the remote-host’

LINUX How to using sql command line

Open a terminal window. Connect to the MySQL server using your root MySQL password and go to the mysql database within it: 1. Create local sql username mysql -u root -p mysql At the mysql> prompt, type: GRANT ALL PRIVILEGES ON *.* TO mary@localhost IDENTIFIED BY 'ship3marker'; then press ENTER. This command string creates a new account on the MySQL server for the user mary. Her password is ship3marker. 2. Create remote sql username GRANT ALL PRIVILEGES ON *.* TO remote@'%' IDENTIFIED BY 'nopass' WITH GRANT OPTION; then press ENTER. This command string is slightly different than the previous one: TO marty@'%' GRANT ALL PRIVILEGES ON *.* TO marty@'%' IDENTIFIED BY 'watch4keys' WITH GRANT OPTION; The % wildcard allows connections on this account from any domain, not just localhost. If you only wanted connections from the visibooks.com domain, you'd use this instead: GRANT ALL PRIVILEGES ON *.* TO marty@visibooks.com IDENTIFIED BY '

LINUX How to create Deamon Shell

Make a deamon shell auto svn update : 1. Open shell terminal 2. vim autoUpdate.sh  3. Add contents: #!/bin/sh while :; do  # your code here  svn update  sleep 5 done 4. Save autoUpdate.sh     :x! 5. Change mod to run     chmod 755 autoUpdate.sh 6. Run Deamon     ./ autoUpdate.sh&

LINUX How to using useradd command

1. Add User without login Example add user tony can not login useradd -s /usr/sbin/nologin tony 2. Add user with Home directory Example add user feel with directory: /var/www/html/feel useradd -d /var/www/html/feel feel 3. Disable shell login Example disable user tom login chsh -s /sbin/nologin tom

LINUX How to use getfacl and setfacl

To know this, first open a terminal and open the folder in which you want to create a subfolder. Next type "mkdir <folder-name>" and press the ENTER key. This will create a folder with default access permissions. To know the access permissions, type   getfacl OfficeDocuments    To set access permissions using  setfacl -m user::rwx,group::rw-,mask:r--,other:--- OfficeDocuments/  Example: set access permissions for usera    setfacl -m u:usera:rwx -R OfficeDocuments /  setfacl -m g:prj_office_documents:rx -R OfficeDocuments /

IOS How to parser xml with XMLReader

NSString *xmlFileContents = [NSString stringWithContentsOfFile:xmlFilePath encoding:NSUTF8StringEncoding error:nil];        NSError *parseError  = nil;     NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:xmlFileContents error:&parseError];    You can download XMLReader at : https://github.com/amarcadet/XMLReader

Cocos2d How to save sprite to image

/* Save image from sprite */ + (void) saveSpriteToImage:(CCSprite*) sprite {         CGSize size = [sprite contentSize];         int nWidth = size.width;     int nHeight = size.height;     CCRenderTexture* render = [CCRenderTexture renderTextureWithWidth:nWidth height:nHeight];     [render begin];     [sprite visit];     [render end];     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);     NSString *documentsDirectory = [paths objectAtIndex:0];     NSString  *pngPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"new%d.png",1]];     [render saveBuffer:pngPath format:kCCImageFormatPNG];     [[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];     [[CCTextureCache sharedTextureCache] removeUnusedTextures]; }

IOS How to encode url

/* encode url when request to server */ + (NSString *) urlEncode:(NSString *)string {     NSString *urlEn = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)string, NULL,                                                                          (CFStringRef)@"!*'();:@&=+$,/?%#[]",                                                                          kCFStringEncodingUTF8 );     return urlEn; }

IOS How to convert HexString to NSString

+ (NSString *) stringFromHexString:(NSString *)hexString {         // The hex codes should all be two characters.     if (([hexString length] % 2) != 0)         return nil;         NSMutableString *string = [NSMutableString string];         for (NSInteger i = 0; i < [hexString length]; i += 2) {                 NSString *hex = [hexString substringWithRange:NSMakeRange(i, 2)];         NSInteger decimalValue = 0;         sscanf([hex UTF8String], "%x", &decimalValue);         [string appendFormat:@"%c", decimalValue];     }         return string; }

IOS How to get data from server with json

/* Get data from Server   */ + (NSDictionary *)getDataFromJson:(NSString *)urlString {        // Execute search by performing an HTTP GET to the REST web service which returns JSON     NSString *jsonString = [Global jsonFromURLString:urlString];     //NSLog(@"jsonString: %@", jsonString);     NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];     // Parse JSON results with TouchJSON.  It converts it into a dictionary.     CJSONDeserializer *jsonDeserializer = [CJSONDeserializer deserializer];     NSError *error = nil;     NSDictionary *resultsDictionary = [jsonDeserializer deserializeAsDictionary:jsonData error:&error];        if(error) return nil;     return resultsDictionary;   } // Get json string from server  + (NSString *)jsonFromURLString:(NSString *)urlString {     NSURL *url = [NSURL URLWithString:urlString];     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];         [request setTimeoutInterval:5.0];     [request

IOS How to post data to server

+ (NSDictionary*)postDataToServer:(NSString *)urlString data:(NSMutableDictionary*) data rError:(NSError**) rError{         NSError **error = nil;     NSDictionary *jsonDict = nil;     NSLog(@"bodyData:%@",data);         CJSONSerializer *jsonSerializer = [CJSONSerializer serializer];     NSData *bodyData = [jsonSerializer serializeDictionary:data error:error];         NSURL *requestURL = [NSURL URLWithString:urlString];     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL];     [request setHTTPMethod: @"POST"];     [request setTimeoutInterval:3.0];     [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];     [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];     [request setValue:[NSString stringWithFormat:@"%d", [bodyData length]] forHTTPHeaderField:@"Content-Length"];     [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];    

IOS How to underline text in UIlabel

You may subclass from UILabel and override drawRect method - ( void ) drawRect :( CGRect ) rect { CGContextRef ctx = UIGraphicsGetCurrentContext (); CGContextSetRGBStrokeColor ( ctx , 207.0f / 255.0f , 91.0f / 255.0f , 44.0f / 255.0f , 1.0f ); CGContextSetLineWidth ( ctx , 1.0f ); CGContextMoveToPoint ( ctx , 0 , self . bounds . size . height - 1 ); CGContextAddLineToPoint ( ctx , self . bounds . size . width , self . bounds . size . height - 1 ); CGContextStrokePath ( ctx ); [ super drawRect : rect ]; }

IOS How to Unzip a file using SSZip

- ( void ) UnzippingZipFile { NSArray * paths = NSSearchPathForDirectoriesInDomains ( NSDocumentDirectory ,     NSUserDomainMask , YES ); NSString * documentsDirectory = [ paths objectAtIndex : 0 ]; NSString * outputPath = [ documentsDirectory stringByAppendingPathComponent :@ "/FolderName" ]; NSString * filePath = [ NSString stringWithFormat :@ "%@/%@" , documentsDirectory ,@ "ZipFile.zip" ]; NSString * zipPath = filePath ; [ SSZipArchive unzipFileAtPath : zipPath toDestination : outputPath delegate : self ]; }   You can download SSZip at : https://github.com/soffes/ssziparchive