python + 自动ssh处理获取日期信息
我需要在我的Linux 5.3上执行一些操作
ssh [Linux machine red hat 5.3] date
为了获取日期结果,在使用ssh连接时需要回答以下问题
- (是/否)? --> 是
- 密码: --> diana_123
然后我就能得到日期结果
请问如何用Python来自动化这个过程?(我在Linux上安装的是Python 2.2.3)
这个Python脚本应该获取IP地址,然后自动连接到103.116.140.151,并返回日期结果
as --> Fri Nov 18 11:25:18 IST 2011
手动操作的例子:
# ssh 103.116.140.151 date
The authenticity of host '103.116.140.151 (103.116.140.151)' can't be established.
RSA key fingerprint is ad:7e:df:9b:53:86:9f:98:17:70:2f:58:c2:5b:e2:e7.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '103.116.140.151' (RSA) to the list of known hosts.
root@10.116.10.151's password:
Fri Nov 18 11:25:18 IST 2011
3 个回答
2
你可以通过在ssh命令中加上StrictHostKeyChecking=no这个参数,来跳过主机密钥的检查:
ssh -oStrictHostKeyChecking=no 103.116.140.151 date
我觉得对于密码来说,不能用同样的方法。正确的做法是使用一种没有密码的限制性密钥来绕过SSH的密码提示:详细信息可以查看这里。
2
最简单的方法就是设置无密码登录。简单来说,就是创建一对本地的ssh密钥,使用以下命令:
ssh-keygen -t rsa
然后把生成的公钥放到 $HOME/.ssh/authorized_keys
文件里,放在 103.116.140.151
这个地址上。如果你不在乎远程主机的密钥,可以加上 -oStrictHostKeyChecking=no
这个ssh选项。
另外,你也可以使用一个叫 Paramiko 的SSH库:
import paramiko
ssh = paramiko.SSHClient()
# Uncomment the following line for the equivalent of -oStrictHostKeyChecking=no
#ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('103.116.140.151', username='user', password='diana_123')
stdin, stdout, stderr = ssh.exec_command("date")
date = stdout.read()
print(date)