4532 发表于 2016-7-29 09:04:41

python操作远程服务器切换到root用户

在自动化运维过程中,需要远程服务器切换到root用户下执行命令,尝试了一些方法,得到如下好用的方法,供大家使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import time
import paramiko

def verification_ssh(host,username,password,port,root_pwd,cmd):
    s=paramiko.SSHClient()
    s.load_system_host_keys()
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    s.connect(hostname = host,port=int(port),username=username, password=password)
    if username != 'root':
      ssh = s.invoke_shell()
      time.sleep(0.1)
      ssh.send('su - \n')
      buff = ''
      while not buff.endswith('Password: '):
            resp = ssh.recv(9999)
            buff +=resp
      ssh.send(root_pwd)
      ssh.send('\n')
      buff = ''
      while not buff.endswith('# '):
            resp = ssh.recv(9999)
            buff +=resp
      ssh.send(cmd)
      ssh.send('\n')
      buff = ''
      while not buff.endswith('# '):
            resp = ssh.recv(9999)
            buff +=resp
      s.close()
      result = buff    else:
      stdin, stdout, stderr = s.exec_command(cmd)
      result = stdout.read()
      s.close()
    return result

if __name__ == "main":
    verification_ssh('192.168.1.11','cimer','1q2w3e4r',22,'1q2w3e4r','ifdown eth0')






页: [1]
查看完整版本: python操作远程服务器切换到root用户