本文主要是介绍python利用paramiko执行服务器命令,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
话不多说直接上代码
封装连接
@staticmethoddef connect(ip, server_user, server_port, server_path):"""连接服务器:param ::return:"""ssh = paramiko.SSHClient()private_key = paramiko.RSAKey.from_private_key_file('{}.ssh/id_rsa'.format(server_path))ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())try:ssh.connect(ip, port=server_port, username=server_user, pkey=private_key, timeout=5, allow_agent=True)return sshexcept Exception as e:app.logger.info('connect_error info is {}'.format(e.__repr__()))return {'result': 1,'ip': ip,'msg': e.__repr__(),}
在服务器执行命令
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
def fabric_run_cmd(self, ip, server_user, server_port, server_path, cmd):"""批量在服务器执行命令:return:"""conn = self.connect(ip, server_user, server_port, server_path)try:if type(conn) == dict:return connelse:stdin, stdout, stderr = conn.exec_command(cmd)app.logger.info('fabric_run_cmd_stdout info is {}'.format(stdout.readlines()))app.logger.info('fabric_run_cmd_stderr info is {}'.format(stderr.readlines()))channel = stdout.channelstatus = channel.recv_exit_status()conn.close()app.logger.info('fabric_run_cmd_status info is {}'.format(status))if status == 0:return {'ip': ip,'msg': '执行成功','result': 0}else:return {'ip': ip,'msg': stderr.readlines(),'result': 1}except Exception as e:app.logger.info('fabric_run_cmd_error info is {}'.format(e.__repr__()))return {'ip': ip,'msg': e.__repr__(),'result': 1}
将文件发送到服务器
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
def fabric_put_file(self, ip, src_file, dst_file, server_user, server_port, server_path):"""发送文件到服务器:return:"""conn = self.connect(ip, server_user, server_port, server_path)if type(conn) == dict:return connelse:try:ftp = conn.open_sftp()ftp.put(dst_file, src_file) # 发送文件之前先判断有没有目标文件夹 如果没有现在服务器上创建文件夹ftp.close() # 在此判断文件是否发送成功return {'ip': ip,'msg': '上传成功','result': 0}except Exception as e:app.logger.info('fabric_put_file_error info is {}'.format(e.__repr__()))return {'ip': ip,'msg': e.__repr__(),'result': 1}
这篇关于python利用paramiko执行服务器命令的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!