创建使用libssh2访问远程服务器的python脚本 - 我想创建访问远程服务器的python脚本,该远程服务器进一步访问同一会话中的另一个服务器。这应该返回一个到主机comp的通道。我想然后执行这个频道中的命令可以说是例如访问数据库。我已经用libssh2库试了但是卡住了。有人可以帮我这个,谢谢
答案 0 :(得分:0)
SSH2的事实上的Python模块是paramiko,它不使用libssh2。
答案 1 :(得分:0)
已经有python binding for libssh2了。也许它可以让你的工作更轻松......
答案 2 :(得分: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