创建使用libssh2访问远程服务器的python脚本-我想制作访问远程服务器的python脚本,该远程服务器在同一会话中进一步访问另一台服务器。这应该将通道返回给主机comp。然后我想执行命令这个频道说例如访问数据库。我已经尝试使用 libssh2 库但卡住了。有人可以帮我解决这个问题,谢谢
问问题
577 次
3 回答
0
SSH2 的事实上的 Python 模块是paramiko,它不使用 libssh2。
于 2013-01-22T19:24:54.460 回答
0
libssh2已经有一个python 绑定。也许它可以使您的任务更轻松...
于 2013-01-22T21:49:49.720 回答
0
带有 Python 绑定的 Libssh2 比 Paramiko 快得多。
Python 绑定:https
://pypi.org/project/ssh2-python/
API:https ://pypi.org/project/ssh2-python/
#!/usr/bin/python3
import socket
import os
import time
from ssh2.session import Session #@UnresolvedImport in eclipse
class ssh_session:
def __init__(self,user, password, host = "localhost",port=22):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
self.s = Session()
self.s.handshake(sock)
self.s.userauth_password(user, password)
self.chan = self.s.open_session()
self.chan.shell()
self.s.set_blocking(False) #switch to non-blocking
self.received_bytes=0
def read(self,minwait=0.01): #10 ms wait are enough for localhost
buf = b"" #when you send simple commands
startread=time.time()
while True:
size, data = self.chan.read()
if size > 0:
buf+=data
self.received_bytes+=size
time.sleep(0.01)
if minwait > 0: # if we have a larger minwait than wait
timedelta = time.time()-startread
if timedelta > minwait:
break
else:
break # non-blocking return with zero minwait
#repeat the while loop until minwait
return (buf.decode())
def write(self,cmd):
self.chan.write(cmd+"\n")
user="<user>"
passwd="<pass>"
contime = time.time()
timedelta = 0
con1 = ssh_session(user,passwd) #create connection instance
#skip banner aka os welcome message
#banner should be done after 1 second or more than 200 received Bytes
while timedelta < 1 and con1.received_bytes < 200:
timedelta = time.time() - contime
con1.read() #just read but do not print
#send command to host
con1.write("pwd")
#receive answer, on localhost connection takes just about 0.3ms
print (con1.read()) #you can pass a minimum wait time in seconds here
#e.g. con1.read(0.8) # wait 0.8 seconds
于 2020-09-14T18:37:32.937 回答