python 切換root 執行命令
阿新 • • 發佈:2018-12-13
如下,以建立系統使用者舉例,
配置檔案配置普通使用者資訊,登入後切換root使用者,建立一個指定名字和密碼的系統使用者:
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)