欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python连接linux

程序员文章站 2024-02-27 16:54:15
...

使用python paramiko库,直接用pip安装pip install paramiko

其简单用法如下代码:

import paramiko

class SSH(object):
	def __init__(self, host, port, user, passwd):
		self.host = host
		self.port = port
		self.user = user
		self.passwd = passwd
		self.length = 0
		self.ssh = paramiko.SSHClient()
		self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
		try:
			self.ssh.onnect(self.host,self.port,self.user,self.passwd)
		except Exception as e:
			print ('Exception:', e)
	def Execmd(self,exe_cmd):
		stdin, stdout, stderr = self.ssh.exec_command(exe_cmd, get_pty = True)
		return stdout.read()
if __name__ == '__main__':
	ssh = SSH(yourip, '22', youruser, yourpasswd)
	ss = ssh.Execmd('cd ~;pwd')
	print(ss)

其结果就会打印出你linux服务器home的目录即:b’/home\r\n’