1、远程执行命令
def remote_execution_command(ip,user,passwd,cmd,Ifsource,loginname=None,get_pty=False):
print_log('INFO','ip : %s,user : %s, cmd : %s start\n' %(ip, user, cmd))
#创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
try:
ssh.connect(hostname=ip, port=22, username=user, password=passwd)
except paramiko.ssh_exception.BadHostKeyException as e:
msg = "the server's host key could not be verified. host: %s" % ip
return (1, '', msg)
except paramiko.ssh_exception.AuthenticationException as e:
msg = 'authentication failed. host: %s' % ip
return (1, '', msg)
except Exception:
msg = 'ssh connect failed. host: %s' % ip
return (1, '', msg)
#source .bash_profile环境变量,不然dbtool dbstate不能用
if Ifsource == True:
new_cmd = 'source /home/%s/.bash_profile; %s'%(user, cmd)
#cmd = "bash -lc '%s'"%(cmd)
# 执行命令
if loginname:
new_cmd = 'su - %s -c "%s"' % (loginname, new_cmd)
if get_pty == True:
stdin, stdout, stderr = ssh.exec_command(new_cmd,get_pty=True)
if get_pty == False:
stdin, stdout, stderr = ssh.exec_command(new_cmd,get_pty=False)
# 获取命令结果
channel = stdout.channel
status = channel.recv_exit_status()
out_data = stdout.read()
err_data = stderr.read()
# 关闭连接
ssh.close()
return(status, out_data, err_data)
2、远程读取文件
def remote_read(ip,user,passwd,file_path):
print_log("INFO", r'remote read ip : %s file : %s'%(ip, file_path))
client = paramiko.SSHClient()
try:
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip, 22, user, passwd)
sftp_client = client.open_sftp()
remote_file = sftp_client.open(file_path, 'r+')
str = remote_file.read()
remote_file.close()
return str
except Exception as e:
print_log('ERROR', 'failed to open the remote file : %s!'%e)
sys.exit(1)
finally:
client.close()
3、远程判断文件是否存在以及创建文件
def remote_dir_state(ip,user,passwd,file_path):
client = paramiko.SSHClient()
try:
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip, 22, user, passwd)
sftp_client = client.open_sftp()
sftp_client.stat(file_path)
print_log("INFO", "folder %s exist do not create it\n"%file_path)
except IOError as e:
print_log("INFO", "folder %s do not exist create it\n"%file_path)
return 0
except Exception as e:
print_log('ERROR', 'failed to check file : %s, %s exit'%(file_path, e))
sys.exit(1)
finally:
client.close()
def remote_mkdir(ip,user,passwd,file_path):
print_log("INFO", r'remote mkdir ip : %s file : %s'%(ip, file_path))
client = paramiko.SSHClient()
try:
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip, 22, user, passwd)
sftp_client = client.open_sftp()
sftp_client.mkdir(file_path)
print_log("INFO", "Create folder %s in remote hosts successfully!"%file_path)
except Exception as e:
print_log("ERROR", "Create folder %s in remote hosts failed! exit"%file_path)
sys.exit(1)
finally:
client.close()
更多操作可以参考这里
paramiko