我需要创建一个自动向OpenSSH ssh客户端输入密码的脚本。

假设我需要使用密码a1234b SSH到myname@somehost。

我已经试过了……

#~/bin/myssh.sh
ssh myname@somehost
a1234b

...但这并不奏效。

如何将此功能放入脚本中?


当前回答

如此:

#!/usr/bin/expect -f
spawn ssh USERNAME@SERVER "touch /home/user/ssh_example"
expect "assword:"
send "PASSWORD\r"
interact

但是! !如果出现如下错误,只需使用expect而不是bash启动脚本,如下所示 而不是bash mysh .sh

/bin/myssh.sh: 2: spawn: not found /bin/myssh.sh: 3: expect: not found /bin/myssh.sh: 4: send: not found /bin/myssh.sh: 5: expect: not found /bin/myssh.sh: 6: send: not found

其他回答

安全性更高的Sshpass

我在寻找ssh进入瘫痪服务器的方法时偶然发现了这个线程——处理ssh连接尝试花了一分钟多,在我输入密码之前超时了。在本例中,我希望能够在提示可用时立即提供我的密码。

(如果还不清楚的话:服务器处于这种状态,再设置公钥登录就太迟了。)

Sshpass来救援。但是,有比sshpass -p更好的方法。

我的实现直接跳到交互式密码提示(不会浪费时间查看是否可以进行公钥交换),并且从不以纯文本的形式显示密码。

#!/bin/sh
# preempt-ssh.sh
# usage: same arguments that you'd pass to ssh normally
echo "You're going to run (with our additions) ssh $@"

# Read password interactively and save it to the environment
read -s -p "Password to use: " SSHPASS 
export SSHPASS

# have sshpass load the password from the environment, and skip public key auth
# all other args come directly from the input
sshpass -e ssh -o PreferredAuthentications=keyboard-interactive -o PubkeyAuthentication=no "$@"

# clear the exported variable containing the password
unset SSHPASS

我想我没有看到任何人提出这个建议,而操作人员只是说“脚本”,所以……

我需要解决同样的问题,而我最舒服的语言是Python。

我用了paramiko图书馆。此外,我还需要使用sudo发布需要升级权限的命令。事实证明,sudo可以通过“-S”标志通过stdin接受其密码!见下文:

import paramiko

ssh_client = paramiko.SSHClient()

# To avoid an "unknown hosts" error. Solve this differently if you must...
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# This mechanism uses a private key.
pkey = paramiko.RSAKey.from_private_key_file(PKEY_PATH)

# This mechanism uses a password.
# Get it from cli args or a file or hard code it, whatever works best for you
password = "password"

ssh_client.connect(hostname="my.host.name.com",
                       username="username",
                       # Uncomment one of the following...
                       # password=password
                       # pkey=pkey
                       )

# do something restricted
# If you don't need escalated permissions, omit everything before "mkdir"
command = "echo {} | sudo -S mkdir /var/log/test_dir 2>/dev/null".format(password)

# In order to inspect the exit code
# you need go under paramiko's hood a bit
# rather than just using "ssh_client.exec_command()"
chan = ssh_client.get_transport().open_session()
chan.exec_command(command)

exit_status = chan.recv_exit_status()

if exit_status != 0:
    stderr = chan.recv_stderr(5000)

# Note that sudo's "-S" flag will send the password prompt to stderr
# so you will see that string here too, as well as the actual error.
# It was because of this behavior that we needed access to the exit code
# to assert success.

    logger.error("Uh oh")
    logger.error(stderr)
else:
    logger.info("Successful!")

希望这能帮助到一些人。我的用例是在大约300台服务器上创建目录、发送和解压文件以及启动程序。因此,自动化至关重要。我试过sshpass, expect,然后想到了这个。

我得到了这个工作如下

.ssh/config被修改以消除是/否提示-我在防火墙后面,所以我不担心欺骗ssh密钥

host *
     StrictHostKeyChecking no

为expect创建一个响应文件,即answer.expect

set timeout 20
set node [lindex $argv 0]
spawn ssh root@node service hadoop-hdfs-datanode restart

expect  "*?assword {
      send "password\r"   <- your password here.

interact

创建bash脚本并在文件中调用expect

#!/bin/bash
i=1
while [$i -lt 129]    # a few nodes here
  
  expect answer.expect hadoopslave$i

  i=[$i + 1]
  sleep 5

done

获取128个用新配置刷新的hadoop datanode -假设您正在为hadoop/conf文件使用NFS挂载

希望这能帮助到一些人——我是一个Windows傻瓜,这花了我大约5个小时才弄明白!

在ubuntu linux -

ssh username@server_ip_address -p port_number

按enter键,然后输入服务器密码

如果您不是root用户,请在命令的开头添加sudo

Solution1:使用sshpass

#~/bin/myssh.sh
sshpass -p a1234b ssh myname@somehost

您可以通过

# Ubuntu/Debian
$ sudo apt-get install sshpass

# Red Hat/Fedora/CentOS
$ sudo yum install sshpass

# Arch Linux
$ sudo pacman -S sshpass

#OS X
brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb

或从这里下载源代码

tar xvzf sshpass-1.08.tar.gz 
cd sshpass-1.08.tar.gz 
./configure
sudo make install

解决方案2:设置SSH无密码登录

假设您需要使用密码2b2b2b从aaa@1.1.1.1(客户端服务器A) SSH到bbb@2.2.2.2(远程服务器B)。

在A中使用如下命令生成公钥(.ssh/id_rsa.pub)和私钥(.ssh/id_rsa)

ssh-keygen -t rsa
[Press enter key]
[Press enter key]
[Press enter key]

使用以下命令将生成的公钥(.ssh/id_rsa.pub)以文件名authorized_keys分发到bbb的.ssh目录下的服务器B

ssh-copy-id bbb@2.2.2.2

第一次ssh登录需要输入密码,以后会自动登录,不需要再次输入!

ssh bbb@2.2.2.2 [Enter]
2b2b2b

然后你的剧本就可以

#~/bin/myssh.sh
ssh myname@somehost