Passwordless authentication to remote systems

Sometimes, you’ll be faced with writing a script that goes off, collects some information from a remote system, and copies that information to another remote system for off-site storage.  Such an example would be the configuration information of remote unix systems, a backup server or the configuration of a san/nas storage device on your network.

In order to run this job as an automated task, you need to be able to connect securely to the remote systems before copying configuration data over the network, but don’t want to have to enter passwords manually, and shouldn’t include passwords in your scripts either (for security reasons), so how do you do it?

You can use ssh keys to do it.

ssh keys are a pair of keys that can be generated for any given user account (called public key and private key), and the private key is then securely copied to the remote system, so that when a connection attempt is made to that remote system by the user offering their public key, the two keys are put together on the remote system to form a successful means of authenticating to that remote system, just like a normal password, but it’s all done by the systems with no interaction required by the user.

If that sounded complicated, it wasn’t meant to.  And it isn’t.  In summary, setting this passwordless authentication mechanism up goes like this…

1. Generate keys for my user using ssh-keygen

2. Copy the keys to the remote system using ssh-copy-id

3. ssh to the remote system to test.  Voila!

A real-world working example of copying the contents of someuser‘s ~/.ssh/id-rsa.pub public key to a remote nas device’s /home/someuser/.ssh/authorized-keys file is shown below with the input required from the sysadmin shown in bold.

myuser@myserver.cyberfella.co.uk 5$ su – someuser
Password:
[someuser@myserver ~]$ pwd
/local/home/someuser
[someuser@myserver ~]$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/local/home/someuser/.ssh/id_rsa):
Created directory ‘/local/home/someuser/.ssh’.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /local/home/someuser/.ssh/id_rsa.
Your public key has been saved in /local/home/someuser/.ssh/id_rsa.pub.
The key fingerprint is:
d2:4b:53:80:4e:17:32:b1:1b:d3:d3:5c:9c:41:6a:94 someuser@myserver.cyberfella.co.uk
[someuser@myserver ~]$ cd .ssh
[someuser@myserver ~/.ssh]$ ls
id_rsa  id_rsa.pub
[someuser@myserver ~/.ssh]$ ssh-copy-id -i ~/.ssh/id_rsa.pub mynas
36
Warning: Permanently added ‘mynas,192.168.0.69’ (RSA) to the list of known hosts.
A customized version of the Linux operating system is used on the
EMC(R) VNX(TM) Control Station.  The operating system is
copyrighted and licensed pursuant to the GNU General Public License
(“GPL”), a copy of which can be found in the accompanying
documentation.  Please read the GPL carefully, because by using the
Linux operating system on the EMC Celerra you agree to the terms
and conditions listed therein.

EXCEPT FOR ANY WARRANTIES WHICH MAY BE PROVIDED UNDER THE TERMS AND
CONDITIONS OF THE APPLICABLE WRITTEN AGREEMENTS BETWEEN YOU AND EMC,
THE SOFTWARE PROGRAMS ARE PROVIDED AND LICENSED “AS IS” WITHOUT
WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE.  In no event will EMC Corporation be liable to
you or any other person or entity for (a) incidental, indirect,
special, exemplary or consequential damages or (b) any damages
whatsoever resulting from the loss of use, data or profits,
arising out of or in connection with the agreements between you
and EMC, the GPL, or your use of this software, even if advised
of the possibility of such damages.

EMC, VNX, Celerra, and CLARiiON are registered trademarks or trademarks of
EMC Corporation in the United States and/or other countries. All
other trademarks used herein are the property of their respective
owners.

EMC VNX Control Station Linux release 3.0 (NAS 7.0.53)
someuser@mynas’s password:
Warning: No xauth data; using fake authentication data for X11 forwarding.
Now try logging into the machine, with “ssh ‘mynas'”, and check in:

.ssh/authorized_keys

to make sure we haven’t added extra keys that you weren’t expecting.

[someuser@myserver ~/.ssh]$

myserver.cyberfella.co.uk 102# cd /etc
myserver.cyberfella.co.uk 103# vi cron.allow
myserver.cyberfella.co.uk 104# su – someuser
[someuser@myserver ~]$ crontab -e
no crontab for someuser – using an empty one

crontab: installing new crontab
[someuser@myserver ~]$ crontab -l
45 23 * * * /local/home/someuser/myscript.sh >/dev/null 2>&1
[someuser@myserver ~]$

 

Example commands in myscript.sh that work due to the passwordless authentication mechanism being in place are…

Backup myNAS information…

/usr/bin/scp -p -o ConnectTimeout=300 someuser@mynas:/celerra/backup/nasdb_backup.1.tar.gz /home/someuser/nasdb_backup.1.tar.gz

/usr/bin/ssh -q someuser@mynas “export NAS_DB=/nas;/nas/bin/server_mount mydatamover ” | grep rw | grep -v “^root_fs_” >> ~/mynas_db_backup

/usr/bin/ssh -q someuser@mynas “export NAS_DB=/nas;/nas/bin/server_export  ALL ” >> ~/mynas_db_backup

/usr/bin/ssh -q someuser@mynas “export NAS_DB=/nas;/nas/bin/nas_replicate -list ” >> ~/mynas_db_backup

Backup myNAS Network Information…

/usr/bin/ssh -q someuser@mynas “export NAS_DB=/nas;/nas/bin/server_ifconfig server_2 -all ” >> ~/mynas_db_backup

Backup myNAS Quota information…

/usr/bin/ssh -q someuser@mynas “export NAS_DB=/nas;/nas/bin/nas_quotas -list -mover mydatamover” >> ~/mynas_db_backup

/usr/bin/ssh -q someuser@mynas “export NAS_DB=/nas;/nas/bin/nas_quotas -report -mover mydatamover” >> ~/mynas_db_backup

/usr/bin/ssh -q someuser@mynas “export NAS_DB=/nas;/nas/bin/server_df ALL | grep -iv CKPT” >> ~/mynas_db_backup

 

Adding SSH Key to Cisco MDS Switch

If you have a script that goes off to a Cisco MDS switch, retreives some information and writes it back to a server, then you’d need to copy the ssh key to the switch, just like you would to a remote unix server for the purpose of passwordless authentication during the initial ssh connection.  Adding a public key to a cisco switch is done like this…

config t

username admin sshkey ssh-rsa <contents of id-rsa.pub here>

It’ll tell you if the key has been added successfully or not.

Deleting a SSH Key from Cisco MDS Switch

To subsequently remove an ssh public key from the switch, use…

no username admin sshkey ssh-rsa <contents of id-rsa.pub here>

 

Troubleshooting SSH connections

You may find yourself having issues with connecting as root or any other user for that matter.  Despite having created and copied you public keys to the remote systems, you’re still being prompted for passphrases or passwords for the user, defeating the whole point of setting up passwordless authentication.

Here’s a quick checklist of things to look out for and ways to troubleshoot the connection.

service stop sshd && /usr/sbin/sshd -d  (restart sshd in debug mode on the remote machine)

ssh -vv <remote-host> (connect to the remote host using ssh in verbose mode)

Before Googling the errors, make sure you can confirm the following:

When you generated the public keys using ssh-keygen you left the passphrase blank.

When you copied the keys over to the remote machine using ssh-copy-id you used the full path to the id_rsa.pub file.  If you’re root, it’s quite probable you copied another users ssh keys over instead of your own!

The .ssh directory in the users home directory has 700 permissions and the authorized-keys file has 600 permissions.

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

Manipulating Files in Linux

RHCE 2: Manipulating files in Linux.  The following blog post is a concise summary of how one can interact with files on a Linux system.  In fact the information contained herein applies to all Linux and UNIX.  By my own admission, if you learn everything contained in this one post of the many posts on my blog, you’ll be well on your way when it comes to turning your hand to any UNIX or Linux system.  Basic but essential knowledge.

Creating a file

“Everything is a file”.  You’ll hear that said about UNIX and/or Linux.  Unlike Windows, there is no registry, just the filesystem.  As such, everything is represented by a file somewhere in the filesystem.  More on the different types of file later.

cat, touch, vi, vim, nano, tee and > (after a command) are all used to create files.    tee is special since when you pipe a command into tee, it will write standard input to standard output as well as displaying the results on screen (using > would hide output to the screen as it redirects it to a file instead).

Listing files

ls, ll, ll -i (displays inode of the file) commands are used with many possible switches to display directory listings.  e.g. ls -al (long listing showing permissions, including hidden files)  ls -lart (same but sorted in reverse date order too) are common uses of the ls command.

Display contents of a file

cat, more, less, head, tail, view, vi, vim, nano, uniq and strings are all commands used to display files in similar but slightly different ways, i.e. in their entirety, a page at a time, the top lines, the bottom lines, in an editor, just unique lines of the file and just ascii text (not binary information) contained within a file.

Copy or Rename a file

cp, rsync, tar, cpio, mv   -can all be used to copy files, move files or rename files.  In Linux, you don’t rename a file, you move it.

Remove a file

rm, erase, rmdir (if it’s a directory, though rm -r will recurse through the tree removing subdirectories as well as files contained beneath the specified starting point.  This is dangerous, especially when used with rm -rf to force it.)

Ownership and Permissions

Like Windows, files have an owning user, they also have an owning group attribute as well as permissions that dictate what level of access the owning user, owning group and everyone else has to the file (or directory).  This is slightly different to Windows, whereby permissions can be set on multiple groups added to the ACL (access control list) of a file (or directory) and takes some getting used to.

To change owner or group use the chown and chgrp commands, or just the chown user:group command to do both in one go.

To change the permissions, use the chmod command.

-rwxrwxrwx    where – means regular file (more on different file types later), then the first rwx is read, write, execute permissions of the owner, the second rwx is the same for the group and the third rwx is everyone else.  Each permission bit has a value

– 421 421 421

So to set permissions of owner full access, group read, everyone read i.e. rwxr–r– would be 4+2+1, 4, 4 i.e. 744 so chmod 744 filenameFull access for everyone would be chmod 777 filename.

Types of file

Regular   (ascii or binary)

Executable   (allowed to execute)

Directory   (contains one or more files)

Symlink   (hard or soft link to another file – hard has it’s own inode but is still linked, soft shares the inode of the linked file.  ln -s realfile linkfile is a common use.  It’s common to get the order the wrong way around.)

Device   (character/raw or block special files are used to send streams of data to kernel modules which controls the sending of the data stream to hardware, e.g. a volume group has a character special file, a disk device has a block special file)

Named Pipe (fifo – first in first out used to send one-way streams of data to other processes (inter-process communication or IPC).

Socket    -a two-way named pipe.  Used for system services for example, whereby information is received and transmitted.

File attributes

Besides permissions that control access to a file, files on a Linux system can also have attributes applied to them that controls what can and can’t be done to the file – even by the root user.

stat   -Display statistics about a file.

wc    -Word count a file (can also be used with wc -l to count lines in a file, or wc -c to count characters)

lsattr    -List attributes of a file.

chattr     -Change attributes of a file.

a   -Can only be appended to

A   -Access time not updated

c    -Auto compress

d    -cannot be backed up by the dump command

D   -contents of the directory are written synchronously to disk

i    -is immutable (cannot be changed or deleted)

j    -is added to the journal before being written to disk on journalling file systems

s    -is securely deleted, i.e. actual data blocks are wiped too

S   -file is synchronously written to disk

u   -undeletable

Pattern matching

The famous grep command is used to simply match lines of text contained in a file, or more cleverly lines containing patterns of text (defined by regular expressions) in a file or files.  More on Regular Expressions will be covered later.

grep -l pattern file1 file2 file3   -finds lines containing pattern in files file1, file2 and file3

grep -n pattern file1    -find the pattern and displays the line numbers where the matches occur.

grep -v     -anything but the pattern matches

grep ^pattern   or    grep pattern$  matches the patterns when they occur at the beginning or the end of the line only.

grep -i   ignores case (because Linux is case sensitive of course)

egrep or grep -E ‘pattern1|pattern2’ file1    -displays either pattern matched

Comparing files

diff, comm and grep are used to compare two files and print matching lines and differing lines, e.g. diff -c file1 file2   displays the output in 3 sections.   comm 123 file1 file2 very similar to diff -c whereby section 1, 2 and/or 3 are suppressed instead of displayed.  Section 1 contains lines unique to file1, section2 contains lines unique to file2 and section3 contains lines in both.  Use of comm takes some getting used to, so read the man page to be sure you’re getting the results you’re after and not something else, or just use diff -c.  comm is very cool tool though, and I find myself using it more than diff.  A new favourite is grep -Fxv -f decommissioned backupclients which would list any lines in a list of backupclients that were not found in the decommissioned list.

Finding files

The find command in UNIX/Linux is fantastic, but like Linux itself, it has a reputation for having a steep learning curve.  I’ll try to make it easy by keeping this short and sweet.

find path option action   where option and action have values and commands specifed respectively, i.e. find path option value action command

e.g. find ./ -size -1G -exec ls -al {} \;     find     ./      -size -1G      -exec ls -al {} \;   will find files from the present working directory down that are less than 1Gb and will long list any matches

other options are

-name     match names (can also use regular expressions like grep)

-atime     last accessed time

-user       owning user is

-mtime    last modified time

-ctime     change time

-group     owning group

-perm     permissions are e.g. 744

-inum     inode number is

-exec can be replaced with -ok or -print to keep the command simpler for simpler finding requirements.  -exec can execute any command upon the files found that match the specified matched conditions, e.g. ls, cp, mv or rm (very dangerous).

the locate command can also be used to find files.  for executable binary commands, it might be quicker to use which or whereis to display the path of the binary that would be executed if the full path was not specified (relying upon the PATH environment variable to locate and prioritise.  Also check for any command aliases in your ~/.profile and ~/.bashrc if whereis or which turns nothing up as a command alias by one name may be calling a binary by another name.  I begin to digress!

Sorting files

sort

sort -k2 -n    -sort on column 2, numerically (useful if the file contains columns of data).  Can also be used to sort by month, e.g. ls -al | sort -k 6M  and use -o outputfile to write results to a file rather than > or >>

Extracting data from a file

cut and awk can be used to extract delimited lines of data from a file or columns of data from a file respectively, e.g.

cat filename | cut -d, -f3 filename     -displays the third key in a comma delimited file

cat filename | awk {‘print $3’}    -displays the third column in a file

Translating data in a file

sed and tr are stream editors for filtering and transforming text and translating or deleting characters respectively.  many great examples of sed are to be found on the internet.

a simple example of sed would be echo day | sed s/day/night/ to convert all occurrences of the word day into night.

a similar, simple example of tr would be tr “day” “night” < input.txt > output.txt

 

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

Linux Essentials

RHCE 1:  Linux Essentials.  The following are the basic commands every newcomer to Linux should understand before building their repertoire on the way to becoming a Linux systems admin.

This post is logically the first in a series of posts to come, walking right around Linux, focussing on RedHat Enterprise Linux.

Connecting to a remote Linux System

telnet, ssh, rlogin

Listing the contents of a filesystem

ls -a     Show hidden files also

ls -F     Show file types i.e. / is a directory, * is a binary and @ is a symbolic link

ls -lh     Show a long listing (contains permissions etc in a human friendly format)

ls -ld     Show a long listing of directorys only (ignore files)

ls -R     Show listing, recursing into subdirectories (large output can be expected)

ls -t     Sort listing with newest first

ls -tr     Sort listing with oldest first (reverse)

List users on the system

w     The what command.  Displays detailed user info like a combination of who and top for the specified user account

who     Display logged in users

who am i     Display info about your logged in user account who executed the command

whoami     Display your username

logname     Show the real username of logged in user (e.g. is su or sudo to another user account)

tty     Display pseudo terminal that you’re logged into e.g /dev/pts/1

id     Display UID for your user account (and gid)

groups     Display groups your user account is a member of

Display information about the system

uname     Display information about the operating system

-a -s -n -r -v -m -p -i -o

hostname     Display hostname of the system (also used to set hostname)

date     Displays time and date

/sbin/hwclock     Display and set hardware clock

cal     Display month calendar

uptime     Display current time elapsed since initial booting, number of users logged in and load averages

top     Display top running processes, Shift + M to sort my memory instead of CPU

Display information about commands

which     Display the absolute path to the specified binary executed, e.g. which cat gives /bin/cat

whereis     Display location of binary and location of man pages for specified binary

man     Display manual page for specified command

man 1     Display user commands section of man page for specified command

man 4     Display special files section of man page for specified command

man 5    Display system configuration files section of man page for a given command

man -k or apropos     Displays man pages sections pertinent to specified search keyword

passwd –help or passwd -?     Displays quick help for passwd command or other command

whatis  or man -f   Displays description for config file or binary, e.g. whatis yum.conf gives Config file for yum package mgmt system

 

 

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

Default gateways on UNIX/Linux

“UNIX is UNIX isn’t it?”  How many times have I heard that said?  Well, no it isn’t actually, as most vendors have their own ways of configuring things like networking on their now highly evolved individual flavours of UNIX.  Even Linux differs between distro.

Here’s a quick reference to where the  default gateway is set.  Don’t forget to restart networking.  For more advanced routing, configure static routes (link at bottom of post).

AIX

smitty mktcpip

HPUX

set_parms addl_network

Solaris

Edit the /etc/defaultrouter file

Red Hat Linux

Edit the /etc/sysconfig/network file

Add line GATEWAY=192.168.0.1

Debian/Ubuntu

Edit the /etc/network/interfaces file

Add line gateway 192.168.0.1

Restart Networking

You’ll need to restart networking to make these changes take effect.  This can generally be achieved with the

AIX: Performed within smitty mktcpip

HPUX: /etc/init.d/net restart

Solaris: svcadm restart physical

RedHat: /etc/init.d/network restart or service network restart

Debian/Ubuntu: /etc/init.d/networking restart

Configuring Static Routes in multi-homed systems.

For more advanced networking with systems containing multiple NICs connecting to multiple VLANs and subnetworks, you’ll need to configure static routes to effectively send the data destined for a machine in such-and-such a network out through the correct NIC.  More can be found on this here…

Adding a persistent static route

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

List UIDs of failed files

If you’re copying data from an NFS device, the local root user of your NFS client will not have omnipotent access over the data, and so if the permissions are set with everyone noaccess, i.e. r-wr-w— or similar (ending in — instead of r–) then even root will fail to copy some files.

To capture the outstanding files after the initial rsync run as root, you’ll need to determine the UID of the owner(s) of the failed files, create dummy users for those uids and perform subsequent rsync’s su’d to those dummy users.  You won’t get read access any other way.

The following shell script will take a look at the log file of failures generated by rysnc -au /src/* /dest/ 2> rsynclog and list uid’s of user accounts that have read access to the failed-to-copy data.  (Note: when using rsync, appending a * will effectively miss .hidden files.  Lose the * and use trailing slashes to capture all files including hidden files and directories).

subsequent rsync operations can be run by each of these users in turn to catch the failed data.  This requires the users to be created on the system performing the copy, e.g. useradd -o -u<UID> -g0 -d/home/dummyuser -s/bin/bash dummyuser

This could also easily be incorporated into the script of course.

#!/usr/bin/bash

#Variables Section

    SRC=”/source_dir”
    DEST=”/destination_dir”
    LOGFILE=”/tmp/rsynclog”
    RSYNCCOMMAND=”/usr/local/bin/rsync -au ${SRC}/* ${DEST} 2> ${LOGFILE}”
    FAILEDDIRLOG=”/tmp/faileddirectorieslog”
    FAILEDFILELOG=”/tmp/failedfileslog”
    UIDLISTLOG=”/tmp/uidlistlog”
    UNIQUEUIDS=”/tmp/uniqueuids”

#Code Section

    #Create a secondary list of all the failed directories
    grep -i opendir ${LOGFILE} | grep -i failed ${LOGFILE} | cut -d\” -f2 > ${FAILEDDIRLOG}

    #Create a secondary list of all the failed files
    grep -i “send_files failed” ${LOGFILE} | cut -d\” -f2 > ${FAILEDFILELOG}

    #You cannot determine the UID of the owner of a directory, but you can for a file
    
    #Remove any existing UID list log file prior to writing a new one
    if [ -f ${UIDLISTLOG} ]; then
        rm ${UIDLISTLOG}
    fi

    #Create a list of UID’s for failed file copies    
    cat ${FAILEDFILELOG} | while read EACHFILE; do
        ls -al ${EACHFILE} | awk {‘print $3’} >> ${UIDLISTLOG}
    done

    #Sort and remove duplicates from the list
    cat ${UIDLISTLOG} | sort | uniq > ${UNIQUEUIDS}    

    cat ${UNIQUEUIDS}

exit

Don’t forget to chmod +x a script before executing it on a Linux/UNIX system.

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

Counting number of files in a Linux/UNIX filesystem

cd to the starting directory, then to count how many files and folders exist beneath,

find . -depth | wc -l

although in practice find . | wc -l works just as well leaving off -depth.  Or to just count the number of files

find . -type f | wc -l

Note that on Linux, a better way to compare source and destination directories, might be to count the inodes used by either filesystem.

df -i

Exclude a hidden directory from the file count, e.g. .snapshots directory on a NetApp filer

#find ./ -type f \( ! -name “.snapshot” -prune \) -print | wc -l – Note:  had real trouble with this!

New approach…  :o(

ls -al | grep ^d | awk {‘print $9’} | grep -v “^\.” | while read eachdirectory; do

     find ./ -depth | wc -l

done

Then add up numbers at the end.

Another way to count files in a large filesystem is to ask the backup software.  If you use emc Networker, the following example may prove useful.

sudo mminfo -ot -q ‘client=mynas,level=full,savetime<7 days ago’ -r ‘name,nfiles’

name                         nfiles

/my-large-volume          894084

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

Copying the contents of one filesystem to another.

Sometimes on older operating systems, rsync (first choice for copying files from one filesystem to another) may not be available.  In such circumstances, you can use tar.  If it’s an initial copy of a large amount of data you’re doing, then this may actually be 2 – 4 times faster due to the lack of rsync’s checksum calculations, although rsync would be faster for subsequent delta copies.

timex tar -cf – /src_dir | ( cd /dest_dir ; tar -xpf – )

Add a v to the tar -xpf command if you want to see a scrolling list of files as the files are copied but be aware that this will slow it down.  I prefer to leave it out and just periodically ls -al /dest_dir in another terminal to check the files are being written correctly.  timex at the front of the command will show you how long it ran for once it completes (may be useful to know).

With the lack of verbose output, if you need confirmation that the command is still running, use ps -fu user_name | grep timex although the originating terminal should not have returned a command prompt unless you backgrounded the process with an & upon execution, or CTRL Z, jobs, bg job_id subsequently. Note that backgrounding the process may hinder your collection of timings so is not recommended if you are timing the operation.

Another alternative would be to pipe the contents of find . -depth into cpio -p thus using cpio’s passthru mode…

timex find . -depth | cpio -pamVd /destination_dir

Note that this command can appear to take a little while to start, before printing a single dot to the screen per file copied (the capital V verbose option as opposed to the lowercase v option)

If you wish to copy data from one block storage device to another, it’d be faster to do it at block level rather than file level.  To do this, ensure the filesystems are unmounted, then use the dd command dd if=/dev/src_device of=/dev/dest_device

Do not use dd on mounted filesystems.  You will corrupt the data.

Overall progress can be monitored throughout the long copy process with df -h in a separate command windowprepending the cpio command with timex will not yield any times once the command has completed – but it is faster than both tar or rsync for initial large copies of data.

To perform a subsequent catch-up copy of new or changed files, simultaneously deleting any files from the Destination that no longer exist on the Source for a true “syncronisation” of the two sides, much like a mirror synchronisation, use…

timex ./rsync -qazu –delete /src_dir/* /dest_dir  

Note this will not include hidden files.  To do that, lose the * off the source fs and add a trailing slash to the destination fs

or to catch up the new contents on the Src side to the Dest side and not delete any files on the Dest side that have been deleted on Src, use

rsync -azu –progress /NFS_Src/* /NFS_Dest

a= archive mode; equals –rlptgoD (recursive, links, permissions, times, group, owner and device files preserved)

z = compress file during transfer (optional but generally best practice)

u = update

–progress in place of v (verbose) or q (quiet).  A touch faster and more meaningful than a scrolling list of files going up the screen.

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

FTP backup script

If you have a remote web server, then for a small fee, your hosting company will back it up for you.  This is money for old rope.  If you run Linux at home, then you can back it up yourself – just by transferring the contents to a local folder on your computer using a shell script that performs the ftp transfer, which can be fully automated by adding it to cron (crontab -e)

#!/bin/bash
HOST=’ftp.mywebserver.co.uk‘ # change the ipaddress accordingly
USER=’myftpusername‘ # username also change
PASSWD=’myftpuserpassword‘ # password also change
ftp -n $HOST < quote USER $USER
quote PASS $PASSWD
bin
prompt off
cd /www # this folder contains files to be backed up…
lcd /webserverbackup # this location is the local directory to backup to.
mget *
bye
exit

Don’t forget to change the username, password, ftp server name/ip address and remote and local mount points to suit your requirements.  And don’t forget to chmod +x the ftpbackup.sh script to make it executable.  Finally use crontab -e to add a scheduled job to run this script automatically.  You can also add to it in order to create a readable log file or to warn you via email in the event of an error.

 

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

vi Reference

Anybody can google the answer right?  Correct.  However, not everybody can then apply the solution – especially if it involves editing text files from the command line.  Cue The vi Editor.

Before you attempt to modify a file with vi, take a copy of the file so you have something to fall back on when you get it 1. horribly wrong, then 2. subconsciously quit with :wq! subsequently writing your wrongs back to disk.  D’oh!

 

Navigation

Basic editing                                                   

Esc       Switch to Command Mode

a          Append after cursor

i           Insert before cursor

R          Overtype

u          Undo (maintains history)

x           Delete character under cursor

O          Open a new line

 

Display settings

:set ic               turn search case sensitivity off

:set noic            turn search case sensitivity on

:set nu              turn line numbering on

:set nonu           turn off line numbers

 

Cut, Copy and Paste                                      

dw        Cut whole word

dd         Cut whole line

cw        Change word

4dd       Cut four lines

d4w      Cut four words

yy         Yank (Copy) whole line

y$         Yank from cursor to end of line

y3w      Yank three words

3yy       Yank three lines

p          Paste after cursor

cc         Change whole line

c4l        Change next 4 chars

c4w      Change next 4 words

c$         Change from cursor to end of line

c0         Change from cursor to beginning of line

 

Searching and Replacing                                

/word    find “word” (forwards)

?word   find “word” (backwards)

n          goto next match of “word”

N          goto previous match of word

:s/dog/cat/gi                             find and replace all dogs with cats on this line only, ignoring case

:%s /dog/cat/g                          find dog and replace with with cat on all lines (gl0bally).

:g/mywrod/s//myword/g find ‘mywrod’ and replace it with ‘myword’

:g/matt/s/fooobar/foobar/g         find ‘matt’ and replace ‘fooobar’ with ‘foobar’ on those lines.

 

Saving, Loading and Quitting

Note: hit Esc to enter Command Mode first…

:w        save with current filename

:wq       save and quit

:q         quit

:q!        forcibly quit

:wq!      forcibly write and quit

:r <filename>    read <filename>

 

Setting up vi

On UNIX edit the .exrc file in your home dir…  smd showmatch ic wrapmargin=0 report=1

If your Linux system uses vim instead of vi, then edit .vimrc, not .exrc to get the same result, though in vim it’s probably already set up nicely to start with.

Add syn on in .vimrc to set syntax highlighting on (nice).  Also, set cindent, set autoindent and nu for indentation and line numbering if you want that too.

 

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

Networking on Red Hat Enterprise Linux

The following post is an attempt at covering Linux Network Configuration end-to-end to a “bit better than reasonable level”.  The brevity of the post is by design since it is the sort of post that is mostly referred to as a reference or quick lookup guide to remind me, and others, of the name of that file, or that command that does…

As much as I love UNIX and Linux, since everything is a command or a file, the downside of that is the requirement of the knowledge up front to a certain extent (largely alleviated by Google these days) and in terms of the command line, is not that intuitive, even with the help of man pages.

Sometimes you just need to look something up that you know you’ve done before, but it was a few months ago or a year or two ago and you just need that post to point you back in the right direction.

 

You can configure a NIC on the fly with

ifconfig eth0 ip-address netmask subnet-mask

The permanent configuration that will be read at boot time or when the /etc/init.d/network restart occurs is held in /etc/sysconfig/network-scripts/ifcfg-eth0 etc

If you need to write a config file from scratch, use this as a template/guide

DEVICE=eth0

BOOTPROTO=static

IPADDR=ip-address

NETMASK=subnet-mask

HWADDR=pre-populated-MAC-address

ONBOOT=yes

USERCTL=no

MTU=1500

TYPE=Ethernet

ETHTOOL_OPTS=”

When you’re done, restart networking

/etc/init.d/network restart

and check they all come up.  If not, recheck the ifcfg-eth files in /etc/sysconfig/network-scripts, paying attention to the ONBOOT=yes line.

To test which of your physical nics corresponds to the linux os network device, disconnect a cable and use

ethtool eth0

paying attention to the bottom line which reads “link detected – YES” or “link detected – NO”

If there is a PCI NIC in the system, RHEL may assign it’s ports eth0 and eth1 taking priority over the embedded nics on the system board.  This is generally not an expected behaviour if you’re new to it.

check all network configurations with

ifconfig -a | less

check the DNS addresses are populated in /etc/resolv.conf and perform an nslookup to verify network connectivity as ping packets are often dropped by firewalls.

Setting a default gateway

You can configure a default gateway in /etc/sysconfig/network

e.g. Add the line

GATEWAY=<ip-of-default-router>

Speed and Duplex setting can be viewed using

ethtool eth1

and

dmesg | grep -i duplex

or using mii-tool

Display all active TCP ports along with process ID and name using the port

netstat -atp

Display routing table in numeric form

netstat -r -nr

Display all netstat statistics

netstat -as

List open files that are network related

lsof -i

MAC Address to Device listing

arp -v

Look for connected interfaces “link detected  -yes”

ethtool eth0

Display run levels where networking starts

chkconfig network –list

Display network status

/etc/init.d/network status   or  /sbin/service/network status

Display all network device configuration

ifconfig -a

Useful files where networking configuration is stored

    /etc/hosts       -will overrride other forms of name resolution contained in /etc/nsswitch.conf

/etc/resolv.conf       -contains the IP addresses of DNS servers used for name resolution in TCP/IP networks.

/etc/nsswitch.conf       -controls the order that names are resolved to IP addresses, i.e. files, nis, dns

/etc/sysconfig/network-scripts/ifcfg-eth0

Display interfaces and metrics

netstat -i

Create an SSH tunnel of port 2381 (hpsmh) on remote host to local port (use 1025 up)

ssh -f username@ip_address -L 1025:ip_address:2381 -N

i.e. browsing to http://localhost:1025 is the same as http://remotehost:2381

 Troubleshooting a NIC

Below is an example of a busy backup network interface on a backup server.  Note how its dropping packets etc.

eth4      Link encap:Ethernet  HWaddr 10:1F:74:8B:8F:8X

          UP BROADCAST RUNNING SLAVE MULTICAST  MTU:1500  Metric:1

          RX packets:22053199483 errors:40041 dropped:18775 overruns:46 frame:0

          TX packets:8811133044 errors:0 dropped:0 overruns:0 carrier:0

          collisions:0 txqueuelen:1000

          RX bytes:31314447740529 (28.4 TiB)  TX bytes:6356693939792 (5.7 TiB)

          Memory:fbec0000-fbee0000

 

Possible Causes of Ethernet Errors

Collisions: Signifies when the NIC card detects itself and another server on the LAN attempting data transmissions at the same time. Collisions can be expected as a normal part of Ethernet operation and are typically below 0.1% of all frames sent. Higher error rates are likely to be caused by faulty NIC cards or poorly terminated cables.

Single Collisions: The Ethernet frame went through after only one collision

Multiple Collisions: The NIC had to attempt multiple times before successfully sending the frame due to collisions.

CRC Errors: Frames were sent but were corrupted in transit. The presence of CRC errors, but not many collisions usually is an indication of electrical noise. Make sure that you are using the correct type of cable, that the cabling is undamaged and that the connectors are securely fastened.

Frame Errors: An incorrect CRC and a non-integer number of bytes are received. This is usually the result of collisions or a bad Ethernet device.

FIFO and Overrun Errors: The number of times that the NIC was unable of handing data to its memory buffers because the data rate the capabilities of the hardware. This is usually a sign of excessive traffic.

Length Errors: The received frame length was less than or exceeded the Ethernet standard. This is most frequently due to incompatible duplex settings.

Carrier Errors: Errors are caused by the NIC card losing its link connection to the hub or switch. Check for faulty cabling or faulty interfaces on the NIC and networking equipment.

 

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash: