How to run the sftp command with a password from Bash script?

后端 未结 9 608
礼貌的吻别
礼貌的吻别 2020-11-22 11:55

I need to transfer a log file to a remote host using sftp from a Linux host. I have been provided credentials for the same from my operations group. However, since I don\'t

相关标签:
9条回答
  • 2020-11-22 12:42

    You can use sshpass for it. Below are the steps

    1. Install sshpass For Ubuntu - sudo apt-get install sshpass
    2. Add the Remote IP to your known-host file if it is first time For Ubuntu -> ssh user@IP -> enter 'yes'
    3. give a combined command of scp and sshpass for it. Below is a sample code for war coping to remote tomcat sshpass -p '#Password_For_remote_machine' scp /home/ubuntu/latest_build/abc.war #user@#RemoteIP:/var/lib/tomcat7/webapps
    0 讨论(0)
  • 2020-11-22 12:45

    Another way would be to use lftp:

    lftp sftp://user:password@host  -e "put local-file.name; bye"
    

    The disadvantage of this method is that other users on the computer can read the password from tools like ps and that the password can become part of your shell history.

    A more secure alternative which is available since LFTP 4.5.0 is setting the LFTP_PASSWORDenvironment variable and executing lftp with --env-password. Here's a full example:

    LFTP_PASSWORD="just_an_example"
    lftp --env-password sftp://user@host  -e "put local-file.name; bye"
    

    LFTP also includes a cool mirroring feature (can include delete after confirmed transfer --Remove-source-files):

    lftp -e 'mirror -R /local/log/path/ /remote/path/' --env-password -u user sftp.foo.com
    
    0 讨论(0)
  • 2020-11-22 12:47

    You can use lftp interactively in a shell script so the password not saved in .bash_history or similar by doing the following:

    vi test_script.sh
    

    Add the following to your file:

    #!/bin/sh
    HOST=<yourhostname>
    USER=<someusername>
    PASSWD=<yourpasswd>
    
    cd <base directory for your put file>
    
    lftp<<END_SCRIPT
    open sftp://$HOST
    user $USER $PASSWD
    put local-file.name
    bye
    END_SCRIPT
    

    And write/quit the vi editor after you edit the host, user, pass, and directory for your put file typing :wq .Then make your script executable chmod +x test_script.sh and execute it ./test_script.sh.

    0 讨论(0)
提交回复
热议问题