Bash Script to SSH into a machine without prompting password and without using keys

后端 未结 2 1475
长情又很酷
长情又很酷 2020-12-10 07:59

I realize this question has been asked a few times but I could not find a relevant answer anywhere in my searching.

I am working in a development environment where s

相关标签:
2条回答
  • 2020-12-10 08:17

    You can do this with the expect tool: http://expect.sourceforge.net/

    It's widely available, so depending on your system, the equivalent of sudo apt-get install expect or yum install expect will install it.

    Here's an example of an expect script with ssh. This logs you in and gives you control of the interactive prompt:

    #!/usr/bin/expect
    
    set login "root"
    set addr "127.0.0.1"
    set pw "password"
    
    spawn ssh $login@$addr
    expect "$login@$addr\'s password:"
    send "$pw\r"
    expect "#"
    send "cd /developer\r"
    interact
    

    Here's an example of how to use expect as part of a bash script. This logs in with ssh, cd to /var, runs a script, then exits the ssh session.

    #!/bin/bash
    ...
    
    login_via_ssh_and_do_stuff() {
    
        # build the expect script in bash
    
        expect_sh=$(expect -c "
        spawn ssh root@127.0.0.1
        expect \"password:\"
        send \"password\r\"
        expect \"#\"
        send \"cd /var\r\"
        expect \"#\"
        send \"chmod +x my_script.sh\r\"
        expect \"#\"
        send \"./my_script.sh\r\"
        expect \"#\"
        send \"exit\r\"
        ")
    
        # run the expect script
        echo "$expect_sh"
    }
    

    You can leave these snippets in a script on your local system, and then just alias to the scripts.

    Also: I know you said security isn't an issue, but I'd like to just note, again, that the "proper" way to ssh without using a password is to use a ssh key-pair =)

    0 讨论(0)
  • 2020-12-10 08:24

    Use sshpass which is available in package repositories on major Linux-es.

    For example, when password is in password.txt file:

    sshpass -fpassword.txt ssh username@hostname
    

    sshpass runs ssh in a dedicated tty, fooling it into thinking it is getting the password from an interactive user.

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