话不多说,直接上函数体 ssh.py:
--------------------------------------------------------------------------------------------------------------------------
# -*- coding: utf-8 -*-
import paramiko
def python_ssh(hostname,username,password,**shell):
try:
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 用于允许连接不在known_hosts名单中的主机
s.connect(hostname = hostname,username = username,password = password)
result = {}
for key in shell:
stdin,stdout,stderr = s.exec_command(shell[key])
result[key] = stdout.read(),stderr.read()
s.close()
return result
except:
result = u"无"
return result
---------------------------------------------------------------------------------------------------------------------------
函数写完了,下面就试试效果:
首先从ssh.py中把python_ssh函数导入,然后调用python_ssh函数即可。调用格式为:
python_ssh('hostname','username','password',SHELL1='free',SHELL2='df -h',SHELL3='ls')
其中,hostname是远程主机的IP地址,username是登录主机的用户名,password是用户密码,SHELL1、SHELL2和SHELL3表示自定义的shell命令变量名,之所以用大写,是因为一般大写表示变量,当然你也可以用小写,这里把shell命令赋值给自定义变量的目的是为了存到字典中时,将变量名作为keys,shell命令执行的结果作为values,方便后续调用。