python远程登录Linux执行命令

安装paramiko标准库

pip install pycrypto

pip install paramiko

pip3 install pexpect

 

 

使用密码连接 linux 并执行命令

 

#!/usr/bin/python3

# -*- coding: UTF-8 -*-

 

扫描二维码关注公众号,回复: 6636224 查看本文章

import paramiko

 

def sshclient_execmd(hostname, port, username, password, *execmd):

    #paramiko.util.log_to_file("paramiko.log") #日志路径

    for execmd_cmd in execmd:

        s = paramiko.SSHClient()  # 绑定实例

        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 允许连接不在know_hosts文件中的主机

        s.connect(hostname=hostname, port=port, username=username, password=password)  # 连接远程主机

        stdin, stdout, stderr = s.exec_command (execmd_cmd)  #执行需要执行的Linux命令

        stdin.write("Y")

        b = (stdout.read())

        string=b.decode('utf-8','ignore')  #将bytes 转为 字符串

        print(string)

    s.close()  #退出连接

    return

 

hostname = '2.2.2.129'

port = 22

username = 'root'

password = '123456'

execmd1 = "mkdir -p /opt/123456"

execmd2 = "touch /opt/123456/test.txt"

execmd3 = "ls -l /opt/123456/test.txt"

execmd4 = "fdisk -l"

execmd5 = "df -h"

sshclient_execmd(hostname, port, username, password, execmd1,execmd2,execmd3,execmd4,execmd5)

 

使用密钥连接 linux 并进行文件传输

import paramiko

import sys,os

host='127.0.0.1'

user = 'whl'

s = paramiko.SSHClient()

s.load_system_host_keys()

s.set_missing_host_key_policy(paramiko.AutoAddPolicy())

privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')             # 定义key路径

mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)

# mykey=paramiko.DSSKey.from_private_key_file(privatekeyfile,password='061128')   # DSSKey方式 password是key的密码

s.connect(host,22,user,pkey=mykey,timeout=5)

cmd=raw_input('cmd:')

stdin,stdout,stderr = s.exec_command(cmd)

cmd_result = df -h ,fdisk -l

for line in cmd_result:

        print line,

s.close()

 

使用密码连接 linux 并进行文件传输

import os

import paramiko

host='127.0.0.1'

port=22

user = 'whl'

password = '123456'

ssh=paramiko.Transport((host,port))

privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')

mykey = paramiko.RSAKey.from_private_key_file( os.path.expanduser('~/.ssh/id_rsa'))   # 加载key 不使用key可不加

ssh.connect(username=username,password=password)           # 连接远程主机

# 使用key把 password=password 换成 pkey=mykey

sftp=paramiko.SFTPClient.from_transport(ssh)               # SFTP使用Transport通道

sftp.get('/etc/passwd','pwd1')                             # 下载 两端都要指定文件名

sftp.put('pwd','/tmp/pwd')                                 # 上传

sftp.close()

ssh.close()

猜你喜欢

转载自blog.csdn.net/qq_35751770/article/details/93734858