English 中文(简体)
Python paramiko ssh 树
原标题:python paramiko ssh

i m new on python. 我写了一个脚本, 连接到主机并执行一个命令

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=pw)

print  running remote command 

stdin, stdout, stderr = ssh.exec_command(command)
stdin.close()

for line in stdout.read().splitlines():
    print  %s$: %s  % (host, line)
    if outfile != None:
        f_outfile.write("%s
" %line)

for line in stderr.read().splitlines():
    print  %s$: %s  % (host, line + "
")
    if outfile != None:
        f_outfile.write("%s
" %line)

ssh.close()

if outfile != None:
    f_outfile.close()

print  connection to %s closed  %host

except:
   e = sys.exc_info()[1]
   print  %s  %e

当远程命令不需要 tty 。 我发现一个引用_shell 示例 < a href=> https://stackoverflow.com/ questions/1911690/nested-ssh-session- with- palamiko" 的 SSH 会话与 Paramiko < / a> 一同使用。 i 不喜欢这个解决方案, 因为如果服务器的提示在我的脚本 - & gt; 无限循环或脚本中指定的提示是返回文本 - gt 的字符串 - & gt; 并非所有数据都会收到 。 是否有更好的解决方案可以让 stdout 和 stder 发送到我脚本中的提示?

最佳回答

可在以下网址找到大量paramiko API文件:http://docs.paramiko.org/en/stable/index.html 。

我使用以下方法执行密码保护客户端的命令 :

import paramiko

nbytes = 4096
hostname =  hostname 
port = 22
username =  username  
password =  password 
command =  ls 

client = paramiko.Transport((hostname, port))
client.connect(username=username, password=password)

stdout_data = []
stderr_data = []
session = client.open_channel(kind= session )
session.exec_command(command)
while True:
    if session.recv_ready():
        stdout_data.append(session.recv(nbytes))
    if session.recv_stderr_ready():
        stderr_data.append(session.recv_stderr(nbytes))
    if session.exit_status_ready():
        break

print  exit status:  , session.recv_exit_status()
print   .join(stdout_data)
print   .join(stderr_data)

session.close()
client.close()
问题回答

被接受的答案有问题, 有时( 随机的) 它会从服务器上带来剪切的反应。 我不知道为什么, 我没有调查被接受的答案的错误原因, 因为这个代码对我非常有效 :

import paramiko

ip= server ip 
port=22
username= username 
password= password 

cmd= some useful command  

ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)

stdin,stdout,stderr=ssh.exec_command(cmd)
outlines=stdout.readlines()
resp=  .join(outlines)
print(resp)

stdin,stdout,stderr=ssh.exec_command( some really useful command )
outlines=stdout.readlines()
resp=  .join(outlines)
print(resp)

The code of @ThePracticalOne is great for showing the usage except for one thing: Somtimes the output would be incomplete.(session.recv_ready() turns true after the if session.recv_ready(): while session.recv_stderr_ready() and session.exit_status_ready() turned true before entering next loop)

所以我的想法是,当数据准备退出会议时, 重新检索数据。

while True:
if session.exit_status_ready():
while True:
    while True:
        print "try to recv stdout..."
        ret = session.recv(nbytes)
        if len(ret) == 0:
            break
        stdout_data.append(ret)

    while True:
        print "try to recv stderr..."
        ret = session.recv_stderr(nbytes)
        if len(ret) == 0:
            break
        stderr_data.append(ret)
    break

无密码SSH为我工作

import paramiko

def connect_SSH():
    ssh = paramiko.SSHClient()
    username =  <uname> 
    port = <port-no>
    ip =  <ip-address> 
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip,port,username)

    stdin, stdout, stderr = ssh.exec_command( <cmd> )
    outlines = stdout.readlines()
    resp=  .join(outlines)
    print(resp) 
connect_SSH()

ThePracticalOne - you are hero! I had problems with exec_comm和 (which is a member of Client) I tried to run powershell comm和s over ssh on Windows server, 和 only your example with

client = paramiko.Transport((hostname, port))
client.connect(username=username, password=password)

 while True:
        if session.recv_ready():
            stdout_data.append(session.recv(nbytes))
        if session.recv_stderr_ready():
            stderr_data.append(session.recv_stderr(nbytes))
        if session.exit_status_ready():
            break

帮助我!

###### Use paramiko to connect to LINUX platform############
import paramiko

ip= server ip 
port=22
username= username 
password= password 
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)

--------Connection Established-----------------------------

######To run shell commands on remote connection###########
import paramiko

ip= server ip 
port=22
username= username 
password= password 
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)


stdin,stdout,stderr=ssh.exec_command(cmd)
outlines=stdout.readlines()
resp=  .join(outlines)
print(resp) # Output 




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签