简体   繁体   English

使用子进程的 Python 自动化

[英]Python automation using subprocess

I'm beginner to python and I would like to start with automation.我是 python 的初学者,我想从自动化开始。 Below is the task I'm trying to do.以下是我正在尝试执行的任务。

ssh -p 2024 root@10.54.3.32

root@10.54.3.32's password:

I try to ssh to a particular machine and its prompting for password.我尝试通过 ssh 连接到特定机器并提示输入密码。 But I have no clue how to give the input to this console.但我不知道如何向这个控制台提供输入。 I have tried this我试过这个

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()

If I execute this, output will be like如果我执行这个,输出会像

python auto.py

root@10.54.3.32's password:

But I have no clue how to give the input to this.但我不知道如何为此提供输入。 If some could help me out in this, would be much grateful.如果有人能在这方面帮助我,将不胜感激。 Also could you please help me after logging in, how to execute the commands on the remote machine via ssh.还请您在登录后帮助我,如何通过 ssh 在远程机器上执行命令。

Would proceed with my automation if this is done如果完成,将继续我的自动化

I tried with con.communicate() since stdin is in PIPE mode .我尝试使用con.communicate()因为 stdin 处于PIPE mode But no luck.但没有运气。

If this cant be accomplished by subprocess, could you please suggest me alternate way to execute commands on remote console(some other module) useful for automation ?如果这不能通过子进程完成,您能否建议我在远程控制台(其他一些模块)上执行对自动化有用的命令的替代方法? since most of my automation depends on executin commands on remote console因为我的大部分自动化依赖于远程控制台上的执行命令

Thanks谢谢

I have implemented through pexpect.我已经通过 pexpect 实现了。 You may need to pip install pexpect before you run the code:在运行代码之前,您可能需要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')

This works only on Linux as pexpect is available only for Linux.这仅适用于 Linux,因为 pexpect 仅适用于 Linux。 You may use plink.exe if you need to run on Windows.如果您需要在 Windows 上运行,您可以使用 plink.exe。 paramiko is another module you may try, with which I had few issues before. paramiko是您可以尝试的另一个模块,我之前遇到过一些问题。

I have implemented through paramiko.我已经通过 paramiko 实现了。 You may need to pip install paramiko before you run the code:在运行代码之前,您可能需要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")

If you want to pass command and grab the output, Simply perform the following steps:如果要传递命令并获取输出,只需执行以下步骤:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM