时间长不写Python了,练练手
paramiko和logging模块基本用法和这个差不多
#!/usr/bin/python
#coding=UTF-8
import paramiko
import logging
import re
#使用logging库
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
formatter = logging.Formatter('%(asctime)s--%(levelname)s--%(message)s')
#将日志写入文件
handler = logging.FileHandler('log.txt')
handler.setLevel(level=logging.INFO)
handler.setFormatter(formatter)
logger.addHandler(handler)
#将日志输出到窗口
console = logging.StreamHandler()
console.setLevel(level=logging.INFO)
console.setFormatter(formatter)
logger.addHandler(console)
#使用paramiko库建立ssh连接
class test_paramiko(object):
#初始化连接
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#使用装饰器可以直接调用该函数,不用实例化
@classmethod
def exec_cmd(cls,cmd):
stdin,stdout,stderr = test_paramiko.ssh.exec_command(cmd)
result = stdout.read()
return result
def connect(Username,passwd,IP):
try:
test_paramiko.ssh.connect(username=Username,password=passwd,hostname=IP)
except paramiko.AuthenticationException:
print 'connect failed'
return False
except paramiko.SSHException:
print 'connect failed'
return False
def dis_connect():
test_paramiko.ssh.close()
if __name__ == '__main__':
#打印日志
logger.info('start test!')
#连接到虚拟机,并执行ls命令,可以替换命令
connect(Username='root',passwd='password',IP='192.168.96.225')
res = test_paramiko.exec_cmd('ls')
if re.search('test',res):
print res
dis_connect()