需求:
实现批量操作cmd\上传put\下载get
1.先封装一个类SshRemoteHost,
2.类方法run、do_cmd、do_put、do_get
3.新建conf目录,里面新建三个文件ftp.conf web.conf mysql.conf
import os
import sys
import paramiko
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException, SSHException
import logging
logging.basicConfig(filename='my.log', level=logging.WARN,
format="%(asctime)s-%(filename)s-%(lineno)d- %(levelname)s: %(message)s ")
class SshRemoteHost(object):
"""
1). 实现类似lftp的功能, 只支持一部分的命令, 输入的命令不存在, 则报错;
"""
def __init__(self, host, user, pwd, cmd, port=22):
self.host = host
self.port = port
self.user = user
self.pwd = pwd
self.cmd = cmd # cmd hostname; cmd ls -l; cmd data +%F
def run(self):
# cmd hostname 类的反射机制
cmd_str = self.cmd.split()[0] # cmd
if hasattr(self, 'do_' + cmd_str): # 判断是否有do_cmd方法
getattr(self, 'do_' + cmd_str)()
else:
logging.error("目前不支持该操作.....目前支持cmd, put, get")
print("目前不支持该操作.....目前支持cmd, put, get")
def do_cmd(self):
print("正在执行命令......")
# ssh root@172.25.254.250
# 创建一个ssh对象;
client = paramiko.SSHClient()
# 2. 解决问题:如果之前没有;连接过的ip, 会出现
# Are you sure you want to continue connecting (yes/no)? yes
# 自动选择yes
client.se