Ssh – Username and password in command line with sshfs

linuxsshsshfs

I'm creating a small backup script using sshfs:

sshfs backup_user@target_ip:/home /mnt/backup

Is there a way to include the password in this command?

Or is there another file transfer solution where the login password can be included other than FTP/SFTP?

Best Answer

-o password_stdin do not seem to be working on all systems, for instance freeBSD. etc.

You can also use expect Interpreter, it should work with sshfs and should do the trick.

Another solution would be sshpass, for instance, let say your are backing up directory /var/www

Backing up:

name=$(date '+%y-%m-%d')
mkdir /backup/$name && tar -czvf /backup/$name/"$name.tar.gz" /var/www

uploading backup file to backup server

sshpass -p "your_password" scp -r backup_user@target_ip:/home/ /backup/$name

So it will upload directory with today's backup

But still, as it was said higher, best(safe and simple) way would be to use ssh key pair
The only inconvenience would be that you have to go through the key generation process once on every server you need to pair, but it is better than keeping a password in plain text format on all servers you want to back up :),

Generating a Key Pair the Proper way

  • On Local server

    ssh-keygen -t rsa
    
  • On remote Server

    ssh root@remote_servers_ip "mkdir -p .ssh"
    
  • Uploading Generated Public Keys to the Remote Server

    cat ~/.ssh/id_rsa.pub | ssh root@remote_servers_ip "cat >> ~/.ssh/authorized_keys"
    
  • Set Permissions on Remote server

    ssh root@remote_servers_ip "chmod 700 ~/.ssh; chmod 640 ~/.ssh/authorized_keys"
    
  • Login

    ssh root@remote_servers_ip
    
  • Enabling SSH Protocol v2

    uncomment "Protocol 2" in /etc/ssh/sshd_config

  • enabling public key authorization in sshd

    uncomment "PubkeyAuthentication yes" in /etc/ssh/sshd_config

  • If StrictModes is set to yes in /etc/ssh/sshd_config then

    restorecon -Rv ~/.ssh
    
Related Question