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

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

我已经试过了……

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

...但这并不奏效。

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


当前回答

@abbotto的答案对我不起作用,不得不做一些不同的事情:

Yum install sshpass更改为- RPM -ivh http://dl.fedoraproject.org/pub/epel/6/x86_64/sshpass-1.05-1.el6.x86_64.rpm 使用sshpass的命令修改为- sshpass -p "pass" SSH user@mysite -p 2122

其他回答

在下面的例子中,我将写下我使用的解决方案:

场景:我想用sh脚本从服务器复制文件:

#!/usr/bin/expect
$PASSWORD=password
my_script=$(expect -c "spawn scp userName@server-name:path/file.txt /home/Amine/Bureau/trash/test/
expect \"password:\"
send \"$PASSWORD\r\"
expect \"#\"
send \"exit \r\"
")

echo "$my_script"

这是我登录服务器的方式:

ssp <server_ip>

别名ssp = ' / home / myuser /文件/ ssh_script.sh” 猫/home/myuser/Documents/ssh_script.sh

ssp:

#!/bin/bash

sshpass -p mypassword ssh root@$1

因此:

ssp server_ip

这应该在大多数情况下都有帮助(你需要先安装sshpass !):

#!/usr/bin/bash
read -p 'Enter Your Username: ' UserName;
read -p 'Enter Your Password: ' Password;
read -p 'Enter Your Domain Name: ' Domain;

sshpass -p "$Password" ssh -o StrictHostKeyChecking=no $UserName@$Domain

在ubuntu linux -

ssh username@server_ip_address -p port_number

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

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

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

我需要解决同样的问题,而我最舒服的语言是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,然后想到了这个。