How to ssh from within a bash script?

前端 未结 4 882
温柔的废话
温柔的废话 2020-12-07 13:35

I am trying to create an ssh connection and do some things on the remote server from within the script.

However the terminal prompts me for a password, then opens th

相关标签:
4条回答
  • 2020-12-07 13:41

    What you need to do is to exchange the SSH keys for the user the script runs as. Have a look at this tutorial

    After doing so, your scripts will run without the need for entering a password. But, for security's sake, you don't want to do this for root users!

    0 讨论(0)
  • 2020-12-07 13:42

    There's yet another way to do it using Shared Connections, ie: somebody initiates the connection, using a password, and every subsequent connection will multiplex over the same channel, negating the need for re-authentication. ( And its faster too )

    # ~/.ssh/config 
    ControlMaster auto
    ControlPath ~/.ssh/pool/%r@%h
    

    then you just have to log in, and as long as you are logged in, the bash script will be able to open ssh connections.

    You can then stop your script from working when somebody has not already opened the channel by:

    ssh ... -o KbdInteractiveAuthentication=no ....
    
    0 讨论(0)
  • 2020-12-07 13:44
    1. If you want the password prompt to go away then use key based authentication (described here).

    2. To run commands remotely over ssh you have to give them as an argument to ssh, like the following:

    root@host:~ # ssh root@www 'ps -ef | grep apache | grep -v grep | wc -l'

    0 讨论(0)
  • 2020-12-07 13:48

    If you want to continue to use passwords and not use key exchange then you can accomplish this with 'expect' like so:

    #!/usr/bin/expect -f
    spawn ssh user@hostname
    expect "password:"
    sleep 1
    send "<your password>\r"
    command1
    command2
    commandN
    
    0 讨论(0)
提交回复
热议问题