如下,以创建系统用户举例,
配置文件配置普通用户信息,登入后切换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
38
39
40
41
|
def create_user(root_pwd,username,password): import paramiko result = [] ssh = paramiko.SSHClient() #把要连接的机器添加到known_hosts文件中 ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect( hostname = settings.HOST, port = settings.PORT, username = settings.USERNAME, password = settings.PASSWORD, timeout = 60 , ) sc = ssh.invoke_shell() def exe_cmd(cmd,t = 0.1 ): sc.send(cmd) sc.send( "\n" ) time.sleep(t) resp = sc.recv( 9999 ).decode( "utf8" ) #print "cmd='%s',echo='%s'\n"%(cmd,resp) return resp #切换root账号 resp = exe_cmd( "su root" ,t = 1 ) if resp.endswith(u "密码:" ): resp = exe_cmd(root_pwd) #创建用户 cmd_create_user = "useradd {username} -d /home/{username}" . format ( username = username, ) exe_cmd(cmd_create_user) #修改密码 cmd_change_user_pwd = """echo "{password}" | passwd --stdin {username}""" . format ( username = username, password = password, ) exe_cmd(cmd_change_user_pwd) |
以上这篇python 切换root 执行命令的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/pengwupeng2008/article/details/82218388