Showing posts with label Unix. Show all posts
Showing posts with label Unix. Show all posts

Thursday, 16 October 2025

Extended Arguments (xargs) Unix command




xargs builds and executes command lines from standard input.

While pipe command (|) takes the stdout of the previous command and forwards it to stdin of the next command, xargs takes space-separated strings from that stdin and convert them into arguments of xargs command.

Example:

$ echo "/dirA /dirB" | xargs ls

will be converted to:

ls /dirA /dirB

-n1 causes the command specified by xargs to be executed, taking one argument at a time from its input (arguments can be each in one line or simply separated by spaces or tabs) and running the command separately for each individual item.​ The -n1 option means "use just one argument per command invocation".​ Each item from standard input (for example, a filename from a list) will be passed separately to the command. As a result, the command will be run as many times as there are items in the input, once for each.

Example:

echo -e "a\nb\nc" | xargs -n1 echo

...will produce:

echo a
echo b
echo c

So each invocation receives only one argument from the input.​

This is useful when a command should process only one item at a time, such as deleting files one by one, or when handling commands that cannot accept multiple arguments simultaneously.

-I{} replaces {} in the command with the input item (in the following example that's lambda function name).

In the following example we use -I to replace {} with incoming argument for xarg and then we use $ positional parameters to interpolate inputs for sh:

Let's assume we have previously defined variables like...

AWS_PROFILE=...
AWS_REGION=...
SG_ID=...


aws lambda list-functions \
    --profile "$AWS_PROFILE" \
    --region "$AWS_REGION" \
    --query "Functions[].FunctionName" \
    --output text | \
xargs \
    -n1 \
    -I{} \
    sh -c \
        "aws lambda get-function-configuration \
            --profile \"\$1\" \
            --region \"\$2\" \
            --function-name \"\$3\" \
            --query \"VpcConfig.SecurityGroupIds\" \
            --output text 2>/dev/null | \
        grep \
            -w \"\$4\" && \
        echo \
            \"Found in Lambda function: \$3\"" \
    _ "$AWS_PROFILE" "$AWS_REGION" {} "$SG_ID"


The sh -c command allows passing multiple arguments, which are referenced as $1, $2, $3, and $4 inside the shell script.

The underscore (_) is used as a placeholder for the $0 positional parameter inside the sh -c subshell.

When you use sh -c 'script' arg0 arg1 arg2 ..., the first argument after the script (arg0) is assigned to $0 inside the script, and the rest (arg1, arg2, etc.) are assigned to $1, $2, etc.

In this context, _ is a common convention to indicate that the $0 parameter is not used or is irrelevant. It simply fills the required position so that $1, $2, $3, and $4 map correctly to "$AWS_PROFILE", "$AWS_REGION", {} (the function name), and "$SG_ID".


References:

Thursday, 18 April 2024

Cron Utility (Unix)

cron command-line utility is a job scheduler on Unix-like operating systems. It runs as a daemon (background process).

These scheduled jobs (essentially a commands) are called cron jobs. They are repetitive tasks, scheduled to be run periodically, at certain time or interval.

Cron jobs, together with frequency and time of their execution are defined in cron table (crontab) file.
Each job is defined in its own line which has the following format:


minute (0–59)
# │ ┌───────────── hour (0–23)
# │ │ ┌───────────── day of the month (1–31)
# │ │ │ ┌───────────── month (1–12)
# │ │ │ │ ┌───────────── day of the week (0–6) (Sunday to Saturday;
# │ │ │ │ │                                   7 is also Sunday on some systems)
    *   *   *   *   *  <command to execute>


* means "every"

* * * * * = every minute, every hour, every day, every month
0 * * * * = every full hour, every day (HH:MM = *:0)
0 0 * * * = every midnight (HH:MM=0:0)
0 0 1 * * = once a month on the midnight of the first day of the month
0 10 * * * = every day at 10:00h
*/10 * * * * = every 10 minutes of every hour, every day


$ crontab
crontab: usage error: file name or - (for stdin) must be specified
Usage:
 crontab [options] file
 crontab [options]
 crontab -n [hostname]

Options:
 -u <user>  define user
 -e         edit user's crontab
 -l         list user's crontab
 -r         delete user's crontab
 -i         prompt before deleting
 -n <host>  set host in cluster to run users' crontabs
 -c         get host in cluster to run users' crontabs
 -T <file>  test a crontab file syntax
 -s         selinux context
 -V         print version and exit
 -x <mask>  enable debugging

Default operation is replace, per 1003.2


To list all cron jobs use:

$ crontab -l
* * * * * aws s3 sync ~/dir1/ s3://my-bucket/dir1 --region us-east-1 >> ~/logs/crons/s3_sync.log 2>&1
0 * * * * redis-cli -h redis-cache-group-123.cache.amazonaws.com -p 6345 flushall >> ~/logs/crons/flushRedisCache.log 2>&1
* * * * * ~/path/to/my_script1.sh >> ~/logs/crons/my_script1.sh.log 2>&1
0 0 * * * ~/path/to/my_script2.sh >> ~/logs/crons/my_script2.log 2>&1
0 0 1 * * ~/path/to/my_script3.sh >> ~/logs/crons/my_script3.log 2>&1
0 10 * * * ~/path/to/my_script4.sh >> ~/logs/crons/my_script4.log 2>&1
*/10 * * * * rsync -avhl --delete ~/path/to/source ~/path/to/dest/ >> ~/logs/crons/source_dest_rsync.log 2>&1

crontab file should not be edited with file editors but via crontab:

crontab -l


How to disable some cron job?


Simply comment its line in crontab with #.

How to disable all cron jobs?

Either comment all lines in crontab or 

$ crontab -l > crontab_backup.txt
$ crontab -r


-r = removes the current crontab 

To restore backup crontab:

$ crontab crontab_backup.txt
$ crontab -l


Resources:

cron - Wikipedia

Friday, 14 October 2022

Symbolic Links (symlinks)

 


linux - Find out symbolic link target via command line - Server Fault


What are they?

  • files that contain a reference to another file or directory on the same system
  • like shortcuts on Windows OS


What is their purpose?

  • to avoid copying the same binary (usually a library) at multiple locations but simply creating a symlink where file is required to be
  • various clients might require the same file but with name in different format so instead of having multiple copies of the same file but with different names we'd have multiple symlink, each with the name that satisfies requirements of each service

How do they work?

  • opening/running the symlink would open/run the target file
  • editing the content of the symlink edits the content of the target file
  • if target file is deleted symlink becomes a dangling symlink
  • if symlink is deleted, target file remains unaffected
  • it is possible to create symlink that refers to another symlink [How can I create a symlink which points to another symlink?]


How to create them?

How to: Linux / UNIX create soft link with ln command

Use ln command:

NAME
       ln - make links between files

SYNOPSIS
       ln [OPTION]... [-T] TARGET LINK_NAME   (1st form)
       ln [OPTION]... TARGET                  (2nd form)
       ln [OPTION]... TARGET... DIRECTORY     (3rd form)
       ln [OPTION]... -t DIRECTORY TARGET...  (4th form)

DESCRIPTION
       In the 1st form, create a link to TARGET with the name LINK_NAME.  In the 2nd form, create a link to TARGET in the current directory.  In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.  Create hard links by default, symbolic links with --symbolic.  By default, each destination (name of new link) should not already exist.  When creating hard links,  each  TARGET  must  exist.
       Symbolic links can hold arbitrary text; if later resolved, a relative link is interpreted in relation to its parent directory.

       Mandatory arguments to long options are mandatory for short options too.

       --backup[=CONTROL]
              make a backup of each existing destination file

       -b     like --backup but does not accept an argument

       -d, -F, --directory
              allow the superuser to attempt to hard link directories (note: will probably fail due to system restrictions, even for the superuser)

       -f, --force
              remove existing destination files

       -i, --interactive
              prompt whether to remove destinations

       -L, --logical
              dereference TARGETs that are symbolic links

       -n, --no-dereference
              treat LINK_NAME as a normal file if it is a symbolic link to a directory

       -P, --physical
              make hard links directly to symbolic links

       -r, --relative
              create symbolic links relative to link location

       -s, --symbolic
              make symbolic links instead of hard links

       -S, --suffix=SUFFIX
              override the usual backup suffix

       -t, --target-directory=DIRECTORY
              specify the DIRECTORY in which to create the links

       -T, --no-target-directory
              treat LINK_NAME as a normal file always

       -v, --verbose
              print name of each linked file

       --help display this help and exit

       --version
              output version information and exit

       The  backup  suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.  The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable.
       Here are the values:

       none, off
              never make backups (even if --backup is given)

       numbered, t
              make numbered backups

       existing, nil
              numbered if numbered backups exist, simple otherwise

       simple, never
              always make simple backups

       Using -s ignores -L and -P.  Otherwise, the last option specified controls behavior when a TARGET is a symbolic link, defaulting to -P.


Example:

$ sudo ln -s /usr/local/go/bin/go /usr/local/bin/go

Creating a symlink from one folder to another with different names?


Types of symlinks:

(!) Important: at the time the symlink is being used and resolved, target path (in ls command) is understood as a relative path to the parent directory of the symlink (when it doesn't start with /).

$ pwd
/home/beau
$ ln -s foo/bar.txt bar.txt
$ readlink -f /home/beau/bar.txt
/home/beau/foo/bar.txt

Or:

$ cd foo
$ ln -s foo/bar.txt ../bar.txt


How to list all symbolic links in the current directory?

$ find -type l

[man find]: If no paths are given, the current directory is used.
[How to list all symbolic links in a directory]


# save symlinks and their targets (relative to ./path/to/dir/) in csv file which will also be pushed to S3
cd ./path/to/dir/
find . -type l -ls | awk '{print $11,",",$13}' > symlinks.csv

How do I tell if a folder is actually a symlink and how do I fix it if it's broken?

Here are some ways that can be used to verify symlink:

$ stat ./data-vol/content/app/74.0.1365.76 
  File: ./data-vol/content/app/74.0.1365.76 -> data-vol/content/app/win/x86/74.0.1365.76
  Size: 45              Blocks: 0          IO Block: 4096   symbolic link
Device: fd01h/64769d    Inode: 26479224    Links: 1
Access: (0777/lrwxrwxrwx)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2019-07-12 17:17:09.278071996 +0100
Modify: 2019-07-12 17:17:08.666073171 +0100
Change: 2019-07-12 17:17:08.666073171 +0100
 Birth: -


$ stat -L ./data-vol/content/app/74.0.1365.76 
stat: cannot stat './data-vol/content/app/74.0.1365.76': No such file or directory

$ file -L ./data-vol/content/app/74.0.1365.76 
./data-vol/content/app/74.0.1365.76: cannot open `./data-vol/content/app/74.0.1365.76' (No such file or directory)

$ ls ./data-vol/content/app/74.0.1365.76 
./data-vol/content/app/74.0.1365.76

$ ll ./data-vol/content/app/74.0.1365.76 
lrwxrwxrwx 1 root root 45 Jul 12 17:17 ./data-vol/content/app/74.0.1365.76 -> data-vol/content/app/win/x86/74.0.1365.76

How to see full symlink path

$ readlink -f symlinkName

Hard links


How to create hardlink of one file in different directories in linux

Friday, 15 July 2022

Unix Shell Redirection

Redirection operators > and >> can write into a file or a device.

  • > will overwrite existing file or crate a new file
  • >> will append text to existing file or create a new file

 

Example: redirecting command output into a file

$ touch temp.txt
$ echo "Hello, world!" > temp.txt
$ cat temp.txt
Hello, world!
$ echo "Hello, world!" > temp.txt
$ cat temp.txt
Hello, world!
$ echo "Hello, world!" >> temp.txt
$ cat temp.txt
Hello, world!
Hello, world!

Here are examples where redirect operators crated new files:

$ echo "Hello, world!" > temp2.txt
$ cat temp2.txt
Hello, world!
$ echo "Hello, world!" >> temp3.txt
$ cat temp3.txt
Hello, world!

Devices/files:

0 - stdin (standard input)
1 - stdout (standard output)
2 - stderr (error message output) 
/dev/null - special device (null device) which discards any input

 

Example: discarding command output messages (including error messages)

command > /dev/null 2>$1

2>$1 redirects stderr into stdout and > /dev/null redirects stdout into null device.

More compact version of the above line is:

command  &> /dev/null

&> /dev/null redirects both stdout and stderr into null device.


References:


What does “>” do vs “>>”?

Monday, 21 March 2022

Unix Filesystem Hierarchy



Run man hier to see extensive list of directories and description of the filesystem hierarchy.

/srv

  • owner is root
  • contains site-specific data which is served by this system
  • place for your workspace - your software development tree.
  • code repository (possibly in /srv/sourcerepo or something), and then developers would check out their own working copies into their home directories.
  • place for my source code (though I usually use /srv/vcs/sourcerepo)


/usr

  • the location where Distribution-based items are placed 


/usr/src
  • owner is root
  • Source files for different parts of the system, included with some packages for reference purposes.  Don't work here with your own projects, as files below /usr should be read-only except when installing software (optional).
  • meant for source code for the binaries that come with your system's installation. For example, it could contain the source code for your kernel, tools such as ls, passwd, cp, mv etc, which are all installed BY YOUR DISTRIBUTION. If you upgrade your OS from source, all the source code would go here, when you rebuild your system. You DON'T want to put any software that you install BY YOURSELF in here, because they may get overwritten when you upgrade your system. In general, files that are in /, /usr/bin, /usr/sbin, /bin, /sbin etc. have their source code in /usr/src.
  • is a system directory. You should not change the owner from root for security reasons
  • contains the linux headers and source code of the kernel. Since the system compiles the kernel from there, it IS a security breach to change the ownership to anything other than root
  • if you wanted to recompile an Ubuntu package from source, their package manager would place the source for package in /usr/src/{package dir}


/usr/local

  • owner is root
  • location where you'd place your own localized changesod the Distribution (/usr/local will be empty after a base install)
  • contains the following subdirectories: 
    • bin  
    • etc  
    • games  
    • include  
    • lib  
    • man  
    • sbin 
    • share  
    • src
  • this directory tree is meant to be used for software that you install by yourself, without using the distribution CD(s). For example, /usr/local/bin, /usr/local/sbin are for the binaries that are installed by you separately, /usr/local/etc is for config files etc. Thus /usr/local/src is for source files that you yourself downloaded. Example: go (binary distribution) gets installed in /usr/local/go.
  • If you upgrade your system, files under the /usr tree get overwritten, such as /usr/bin, /usr/sbin, /usr/src etc. However, anything under /usr/local will not be touched. This is why all the software you installed separately should go to /usr/local tree.
  • a place to install files built by the administrator, typically by using the make command (e.g., ./configure; make; make install). The idea is to avoid clashes with files that are part of the operating system, which would either be overwritten or overwrite the local ones otherwise (e.g., /usr/bin/foo is part of the OS while /usr/local/bin/foo is a local alternative).
  • for self, inhouse, compiled and maintained software. 
  • reserved for software installed locally by the sysadmin
  • place where you want to install software along with source files (for other programs to use or for people to look at)
  • It's not meant, however, to be a workspace. Since it is local, you can do whatever you want, of course, but this isn't designed to be the place to put your software development tree.
  • for use by the system administrator when installing software locally.
    It needs to be safe from being overwritten when the system software is updated. 

 

/usr/local/bin

  • for programs that a normal user may run
  • binaries at this path are accessible to all user accounts

 


/usr/local/src

  • owner is root
  • Source code for locally installed software
  • If you downloaded a program not managed by your distribution and wanted to compile/install it, FHS dictates that you do that in /usr/local/src.
  • a good place for downloading third party source code (eg for patching and rebuilding packages), not my own source code


/opt

  • This directory is reserved for all the software and add-on packages that are not part of the default installation. All third party applications should be installed in this directory. (Linux Filesystem Hierarchy: /opt)
  • a directory for installing unbundled packages (i.e. packages not part of the Operating System distribution, but provided by an independent source), each one in its own subdirectory. They are already built whole packages provided by an independent third party software distributor. Unlike /usr/local stuff, these packages follow the directory conventions (or at least they should). For example, someapp would be installed in /opt/someapp, with one of its command being /opt/someapp/bin/foo, its configuration file would be in /etc/opt/someapp/foo.conf, and its log files in /var/opt/someapp/logs/foo.access. (What is the difference between /opt and /usr/local?)
  • for non-self, external, prepackaged binary/application bundle installation
  • directory where you can just toss things and see if they work makes a whole lot of sense. I know I'm not going to go through the effort of packaging things myself to try them out. If the app doesn't work out, you can simply rm the /opt/mytestapp directory and that application is history.
  • used for third-party software, which in the context of Ubuntu, means precompiled software that is not distributed via Debian packages 
  • A program that is installed in /opt is supposed to be self-contained.
  • The main reason for using /opt is to provide a common standard path where external software can be installed without interfering with the rest of the installed system. /opt does not appear in standard compiler or linker paths (gcc -print-search-dirs or /etc/ld.so.conf etc.), so headers and libraries installed there are somewhat isolated from the main system and shouldn't interfere with already-installed programs. (Why should I move everything into /opt?)

 

Resources:

executable - What is /usr/local/bin? - Unix & Linux Stack Exchange

Thursday, 3 March 2022

Secure File Copy (scp) Tool

 scp is used to securely copy files and directories to or from remote machine.

 


$man scp

SCP(1)                                                                                 BSD General Commands Manual                                                                                SCP(1)

NAME
     scp — OpenSSH secure file copy

SYNOPSIS
     scp [-346BCpqrTv] [-c cipher] [-F ssh_config] [-i identity_file] [-J destination] [-l limit] [-o ssh_option] [-P port] [-S program] source ... target

DESCRIPTION
     scp copies files between hosts on a network.  It uses ssh(1) for data transfer, and uses the same authentication and provides the same security as ssh(1).  scp will ask for passwords or
     passphrases if they are needed for authentication.

     The source and target may be specified as a local pathname, a remote host with optional path in the form [user@]host:[path], or a URI in the form scp://[user@]host[:port][/path].  Local file
     names can be made explicit using absolute or relative pathnames to avoid scp treating file names containing ‘:’ as host specifiers.

     When copying between two remote hosts, if the URI format is used, a port may only be specified on the target if the -3 option is used.

     The options are as follows:

     -3      Copies between two remote hosts are transferred through the local host.  Without this option the data is copied directly between the two remote hosts.  Note that this option disables the
             progress meter.

     -4      Forces scp to use IPv4 addresses only.

     -6      Forces scp to use IPv6 addresses only.

     -B      Selects batch mode (prevents asking for passwords or passphrases).

     -C      Compression enable.  Passes the -C flag to ssh(1) to enable compression.

     -c cipher
             Selects the cipher to use for encrypting the data transfer.  This option is directly passed to ssh(1).

     -F ssh_config
             Specifies an alternative per-user configuration file for ssh.  This option is directly passed to ssh(1).

     -i identity_file
             Selects the file from which the identity (private key) for public key authentication is read.  This option is directly passed to ssh(1).


     -J destination
             Connect to the target host by first making an scp connection to the jump host described by destination and then establishing a TCP forwarding to the ultimate destination from there.  Mul‐
             tiple jump hops may be specified separated by comma characters.  This is a shortcut to specify a ProxyJump configuration directive.  This option is directly passed to ssh(1).

     -l limit
             Limits the used bandwidth, specified in Kbit/s.

     -o ssh_option
             Can be used to pass options to ssh in the format used in ssh_config(5).  This is useful for specifying options for which there is no separate scp command-line flag.  For full details of
             the options listed below, and their possible values, see ssh_config(5).

                   AddressFamily
                   BatchMode
                   BindAddress
                   BindInterface
                   CanonicalDomains
                   CanonicalizeFallbackLocal
                   CanonicalizeHostname
                   CanonicalizeMaxDots
                   CanonicalizePermittedCNAMEs
                   CASignatureAlgorithms
                   CertificateFile
                   ChallengeResponseAuthentication
                   CheckHostIP
                   Ciphers
                   Compression
                   ConnectionAttempts
                   ConnectTimeout
                   ControlMaster
                   ControlPath
                   ControlPersist
                   GlobalKnownHostsFile
                   GSSAPIAuthentication
                   GSSAPIDelegateCredentials
                   HashKnownHosts
                   Host
                   HostbasedAuthentication
                   HostbasedKeyTypes
                   HostKeyAlgorithms
                   HostKeyAlias
                   Hostname
                   IdentitiesOnly
                   IdentityAgent
                   IdentityFile
                   IPQoS
                   KbdInteractiveAuthentication
                   KbdInteractiveDevices
                   KexAlgorithms
                   LogLevel
                   MACs
                   NoHostAuthenticationForLocalhost
                   NumberOfPasswordPrompts
                   PasswordAuthentication
                   PKCS11Provider
                   Port
                   PreferredAuthentications
                   ProxyCommand
                   ProxyJump
                   PubkeyAcceptedKeyTypes
                   PubkeyAuthentication
                   RekeyLimit
                   SendEnv
                   ServerAliveInterval
                   ServerAliveCountMax
                   SetEnv
                   StrictHostKeyChecking
                   TCPKeepAlive
                   UpdateHostKeys
                   User
                   UserKnownHostsFile
                   VerifyHostKeyDNS

     -P port
             Specifies the port to connect to on the remote host.  Note that this option is written with a capital ‘P’, because -p is already reserved for preserving the times and modes of the file.

     -p      Preserves modification times, access times, and modes from the original file.

     -q      Quiet mode: disables the progress meter as well as warning and diagnostic messages from ssh(1).

     -r      Recursively copy entire directories.  Note that scp follows symbolic links encountered in the tree traversal.

     -S program
             Name of program to use for the encrypted connection.  The program must understand ssh(1) options.

     -T      Disable strict filename checking.  By default when copying files from a remote host to a local directory scp checks that the received filenames match those requested on the command-line
             to prevent the remote end from sending unexpected or unwanted files.  Because of differences in how various operating systems and shells interpret filename wildcards, these checks may
             cause wanted files to be rejected.  This option disables these checks at the expense of fully trusting that the server will not send unexpected filenames.

     -v      Verbose mode.  Causes scp and ssh(1) to print debugging messages about their progress.  This is helpful in debugging connection, authentication, and configuration problems.

EXIT STATUS
     The scp utility exits 0 on success, and >0 if an error occurs.

SEE ALSO
     sftp(1), ssh(1), ssh-add(1), ssh-agent(1), ssh-keygen(1), ssh_config(5), sshd(8)

HISTORY
     scp is based on the rcp program in BSD source code from the Regents of the University of California.

AUTHORS
     Timo Rinne <tri@iki.fi>
     Tatu Ylonen <ylo@cs.hut.fi>

BSD                                                                                         November 30, 2019 
    


To copy a directory recursively use -r flag:

$ scp -r nvidia@nvidia-nano:/usr/src/tensorrt/samples/python/uff_ssd ~/dev/
nvidia@nvidia-nano's password: 
inference.py                                  100%   12KB   3.3MB/s   00:00    
engine.py                                     100% 5750     4.5MB/s   00:00    
__init__.py                                   100%    0     0.0KB/s   00:00    
boxes.py                                      100% 6725     5.2MB/s   00:00    
coco.py                                       100% 4755     4.2MB/s   00:00    
...

shell - How do I copy a folder from remote to local using scp? - Stack Overflow


To copy file which has spaces in path and/or name use double backslash before space and wrap entire file path in double quotation marks:

~/Downloads$ scp nvidia@nvidia-nano:"/home/nvidia/Pictures/Object\\ Detection\\ -\\ SSD.png" ~/Pictures
nvidia@192.168.0.10's password: 
Object Detection - SSD.png                    100%  444KB   1.2MB/s   00:00 

 
To copy a directory from local to remote:

$ scp -r LocalDir user@19.168.0.61:/home/user/destination

This will create LocalDir in destination folder.
 
 
If public-private key (SSH keys) authentication is used (instead of username/password) we can specify the path to the private key. For the following example we've created key pair for accessing AWS EC2 VM instance, downloaded the private key (.pem) file and can use it to access that VM in order to copy a directory onto it:

~/.ssh$ scp \
-i "my-vm.pem" \
-pr /home/bojan/dev/my-app/ \
ec2-user@50.51.52.53:/home/ec2-user/my-app/

This is how to copy a file from remote (EC2 instance in this case) to a local host (into a current directory):

$ scp \
-i key-pair--ec2--bojan-temp.pem \
ec2-user@ec2-19-208-98-120.compute-1.amazonaws.com:/usr/bin/my_file \
./
 
To copy a single file from local to remote:
 
$ scp \
-i key-pair--ec2--bojan-temp.pem \
my_file \
ec2-user@ec2-19-208-99-120.compute-1.amazonaws.com:/home/ec2-user/
 
 
To copy all files from current directory, we can use *:
 
~/path/to/my-app$ scp \
-i ~/.ssh/my-vm.pem \
-pr * \
ec2-user@50.51.52.53:/home/ec2-user/my-app/
 
app.py                                                                                                                                                                      100% 4921    17.9KB/s   00:00    
Dockerfile                                                                                                                                                                  100%  152     0.9KB/s   00:00    
Makefile                                                                                                                                                                    100%  313     2.1KB/s   00:00    
README.md                                                                                                                                                                   100% 2179     8.1KB/s   00:00    
requirements.txt 

 

scp preserves file/directory attributes e.g. if it was hidden on the origin machine, it will also be hidden on the target machine.

 

Troubleshooting

If SSH server is not installed, not running or firewall blocks incoming connections on port 22 on the remote machine, scp command might fail with this error:

$ scp -r local_dir/ user@remote_host:~/Downloads/
ssh: connect to host remote_host port 22: Connection refused
lost connection

To fix this, we need to have access to the remote machine so we can check if the SSH server is installed and is up and running.
 
The following commands show the case when openssh server is not installed:

To check if sshd process is running:

$ ps -aux | grep sshd
 
To check if there is SSH server config file (which existence is mandatory for running SSH server):

$ cat /etc/ssh/sshd_config
cat: /etc/ssh/sshd_config: No such file or directory


To check which openssh application is installed (the output shows that only SSH client is present):

$ apt list --installed | grep openssh

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

openssh-client/jammy-updates,now 1:8.9p1-3ubuntu0.1 amd64 [installed,automatic]

 
To install SSH server:
 
$ sudo apt install openssh-server

We can now verify again all installed openssh packages:

$ apt list --installed | grep openssh

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

openssh-client/jammy-updates,now 1:8.9p1-3ubuntu0.1 amd64 [installed,automatic]
openssh-server/jammy-updates,now 1:8.9p1-3ubuntu0.1 amd64 [installed]
openssh-sftp-server/jammy-updates,now 1:8.9p1-3ubuntu0.1 amd64 [installed,automatic]

SSH server config is now present:

$ cat /etc/ssh/sshd_config

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

Include /etc/ssh/sshd_config.d/*.conf

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
#HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
#PermitRootLogin prohibit-password
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#PubkeyAuthentication yes

# Expect .ssh/authorized_keys2 to be disregarded by default in future.
#AuthorizedKeysFile    .ssh/authorized_keys .ssh/authorized_keys2

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
KbdInteractiveAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the KbdInteractiveAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via KbdInteractiveAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and KbdInteractiveAuthentication to 'no'.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
PrintMotd no
#PrintLastLog yes
#TCPKeepAlive yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

# override default of no subsystems
Subsystem    sftp    /usr/lib/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#    X11Forwarding no
#    AllowTcpForwarding no
#    PermitTTY no
#    ForceCommand cvs server


Installing openssh-server is enough. If we re-run now scp command, it will be successful.

We can also verify that ssh daemon is listening on port 22:

$ sudo lsof -i :22 
COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
sshd    1737 root    3u  IPv4  30631      0t0  TCP *:ssh (LISTEN)
sshd    1737 root    4u  IPv6  30633      0t0  TCP *:ssh (LISTEN)



How to enforce password-based authentication?


In the following case password authentication was not enabled on the server side so the client received the following error:

ssh user@host
Received disconnect from host port 22:2: Too many authentication failures
Disconnected from host port 22

We can debug it with:

$ ssh user@host -vvv


To enable password-based authentication, we need to edit ssh daemon config on the server side:

$ cat /etc/ssh/sshd_config
...
PasswordAuthentication yes


After that:

$ sudo /etc/init.d/ssh force_reload
$ sudo /etc/init.d/ssh restart


References:

amazon ec2 - How Can I Download a File from EC2 - Stack Overflow

12.04 - Why am I getting a "port 22: Connection refused" error? - Ask Ubuntu

ssh - scp connection refused error - Super User

How to Change SSH Port Number in Linux

ssh - Is it okay when ssh_config does not exist? - Server Fault

Monday, 7 February 2022

read (Unix shell command) Manual

read (Wikipedia)

 

$ read --help
read: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
    Read a line from the standard input and split it into fields.
    
    Reads a single line from the standard input, or from file descriptor FD
    if the -u option is supplied.  The line is split into fields as with word
    splitting, and the first word is assigned to the first NAME, the second
    word to the second NAME, and so on, with any leftover words assigned to
    the last NAME.  Only the characters found in $IFS are recognised as word
    delimiters.
    
    If no NAMEs are supplied, the line read is stored in the REPLY variable.
    
    Options:
      -a array  assign the words read to sequential indices of the array
                variable ARRAY, starting at zero
      -d delim  continue until the first character of DELIM is read, rather
                than newline
      -e        use Readline to obtain the line
      -i text   use TEXT as the initial text for Readline
      -n nchars return after reading NCHARS characters rather than waiting
                for a newline, but honor a delimiter if fewer than
                NCHARS characters are read before the delimiter
      -N nchars return only after reading exactly NCHARS characters, unless
                EOF is encountered or read times out, ignoring any
                delimiter
      -p prompt output the string PROMPT without a trailing newline before
                attempting to read
      -r        do not allow backslashes to escape any characters
      -s        do not echo input coming from a terminal
      -t timeout        time out and return failure if a complete line of
                input is not read within TIMEOUT seconds.  The value of the
                TMOUT variable is the default timeout.  TIMEOUT may be a
                fractional number.  If TIMEOUT is 0, read returns
                immediately, without trying to read any data, returning
                success only if input is available on the specified
                file descriptor.  The exit status is greater than 128
                if the timeout is exceeded
      -u fd     read from file descriptor FD instead of the standard input
    
    Exit Status:
    The return code is zero, unless end-of-file is encountered, read times out
    (in which case it's greater than 128), a variable assignment error occurs,
    or an invalid file descriptor is supplied as the argument to -u.

 

If some command returns a set of strings of interest in a tab separated line we can use read to assign them as elements of an array variable:

$ read -a vars <<<  $(...command...)
$ echo $vars

 
If some command returns 2 strings in a single line and we want to assign them to two variables:
 
$ read var1 var2 <<< "$(...command...)"
$ echo 'var1: ' $var1
$ echo 'var2: ' $var2
  
 
---