Python (automated operation and maintenance) of the remote Linux operating module

 Module: paramiko

Description: You can remotely connect to the server to the remote account password to a remote key, you can also transfer files

#实现远程登录paramiko模块
#ssh账号密码远程连接
#-*-coding:utf-8 -*-
def ssh_paramiko():
    import paramiko
    hostname = '192.168.3.2'
    port = 22
    username = 'root'
    password = ''
    paramiko.util.log_to_file('syslogin.log')					#保存日志
    ssh = paramiko.SSHClient()									#创建连接对象
    ssh.load_system_host_keys()									#获取客户端host_key,默认为“~/.ssh/known_hosts”
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())    #自动添加已知hosts
    ssh.connect(hostname=hostname,port=port,username=username,password=password)	#创建ssh连接
    stdin,stdout,stderr=ssh.exec_command('free -m')				#执行远程命令
    print(stdout.read().decode('utf-8'))					#打印命令执行结果
    ssh.close()								#关闭ssh连接
#ssh_paramiko()
#实现ssh密钥登录
def key_ssh():
	import paramiko
	key = paramiko.RSAKey.from_private_key_file("/root/.ssh/id_rsa")			#定义公钥文件位置
	hostname=""																	#定义远程主机
	prot=""																		#定义远程端口
	username=""
	command=""
	ssh = paramiko.SSHClient()
	ssh.set_missing_host_key__policy(paramiko.AutoAddpolicy())					#设置远程主机没有本地主机密钥或hostkey时的策略“AutoAddpolicy”为自动添加
	ssh.connect(hostname=hostname,port=int(port),username=username,pkey=key)
	stdin,stdout,stder = ssh.exec_command(command)
	print(stdout.read().decode('utf-8'))
#key_ssh()
#实现SFTP上传文件和下载文件
def sftp():
    import paramiko
    username = "root"
    password = ""
    hostname = "192.168.3.2"
    port = "22"
    try:
        t = paramiko.Transport((hostname,int(port)))
        t.connect(username=username,password=password)				#创建一个
        sftp = paramiko.SFTPClient.from_ransport(t)					#创建一个连接对象
        sftp.put("/hello.txt","/date/hello.txt")					#上传文件到服务端
        sftp.get("/date/hello.txt","/hello1.txt")					#下载文件到本地
        sftp.mkdir("/python")										#在服务器端创建文件夹
        sftp.rmdir("/python")										#删除远程主机的目录
        sftp.rename("/hello.txt","/hello2.txt")						#修改远程主机文件名称
        print(sftp.state("/date/hello.txt"))						#打印文件信息
        print(sftp.listdir("/date"))								#打印目录列表
        t.close()													#关闭连接
    except Exception as e:
    	print(str(e))

 

Published 65 original articles · won praise 16 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_41674452/article/details/103975156