我是python的初学者,我想从自动化开始。下面是我正在尝试完成的任务。
ssh -p 2024 root@10.54.3.32
root@10.54.3.32's password:我尝试通过ssh连接到一台特定的机器,它会提示输入密码。但是我不知道如何将输入提供给这个控制台。我已经试过了
import sys
import subprocess
con = subprocess.Popen("ssh -p 2024 root@10.54.3.32", shell=True,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr =subprocess.PIPE)
print con.stdout.readlines()如果我执行此命令,输出将如下所示
python auto.py
root@10.54.3.32's password:但是我不知道如何给出输入。如果有人能帮我解决这个问题,我将不胜感激。还可以请您帮助我登录后,如何通过ssh在远程机器上执行命令。
如果这样做了,我会继续我的自动化。
因为标准输入在PIPE mode中,所以我尝试使用con.communicate()。但没那么走运。
如果这不能通过子进程完成,你能建议我在远程控制台(一些其他模块)上执行自动化有用的命令的替代方法吗?因为我的大部分自动化都依赖于远程控制台上的执行命令
谢谢
发布于 2016-12-02 00:11:34
我已经通过pexpect实现了。在运行代码之前,您可能需要执行pip install pexpect:
import pexpect
from pexpect import pxssh
accessDenied = None
unreachable = None
username = 'someuser'
ipaddress = 'mymachine'
password = 'somepassword'
command = 'ls -al'
try:
ssh = pexpect.spawn('ssh %s@%s' % (username, ipaddress))
ret = ssh.expect([pexpect.TIMEOUT, '.*sure.*connect.*\(yes/no\)\?', '[P|p]assword:'])
if ret == 0:
unreachable = True
elif ret == 1: #Case asking for storing key
ssh.sendline('yes')
ret = ssh.expect([pexpect.TIMEOUT, '[P|p]assword:'])
if ret == 0:
accessDenied = True
elif ret == 1:
ssh.sendline(password)
auth = ssh.expect(['[P|p]assword:', '#']) #Match for the prompt
elif ret == 2: #Case asking for password
ssh.sendline(password)
auth = ssh.expect(['[P|p]assword:', '#']) #Match for the prompt
if not auth == 1:
accessDenied = True
else:
(command_output, exitstatus) = pexpect.run("ssh %s@%s '%s'" % (username, ipaddress, command), events={'(?i)password':'%s\n' % password}, withexitstatus=1, timeout=1000)
print(command_output)
except pxssh.ExceptionPxssh as e:
print(e)
accessDenied = 'Access denied'
if accessDenied:
print('Could not connect to the machine')
elif unreachable:
print('System unreachable')这只适用于Linux,因为pexpect仅适用于Linux。如果你需要在Windows上运行,你可以使用plink.exe。paramiko是您可以尝试的另一个模块,我之前使用它时遇到了一些问题。
发布于 2020-01-27 19:39:40
我已经通过paramiko实现了。在运行代码之前,您可能需要执行pip install paramiko:
import paramiko
username = 'root'
password = 'calvin'
host = '192.168.0.1'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=str(username), password=str(password))
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
chan = ssh.invoke_shell()
time.sleep(1)
print("Cnnection Successfully")如果您想要传递命令并抓取输出,只需执行以下步骤:
chan.send('Your Command')
if chan is not None and chan.recv_ready():
resp = chan.recv(2048)
while (chan.recv_ready()):
resp += chan.recv(2048)
output = str(resp, 'utf-8')
print(output)https://stackoverflow.com/questions/40914325
复制相似问题