python 切换root 执行命令的方法

yipeiwu_com5年前Python基础

如下,以创建系统用户举例,

配置文件配置普通用户信息,登入后切换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)
 

以上这篇python 切换root 执行命令的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python操作MongoDB数据库的方法示例

本文实例讲述了Python操作MongoDB数据库的方法。分享给大家供大家参考,具体如下: >>> import pymongo >>> clie...

python使用threading获取线程函数返回值的实现方法

threading用于提供线程相关的操作,线程是应用程序中工作的最小单元。python当前版本的多线程库没有实现优先级、线程组,线程也不能被停止、暂停、恢复、中断。 threading模...

Python定时器实例代码

在实际应用中,我们经常需要使用定时器去触发一些事件。Python中通过线程实现定时器timer,其使用非常简单。看示例: import threading def fun_timer...

Python 代码性能优化技巧分享

Python 代码性能优化技巧分享

如何进行 Python 性能优化,是本文探讨的主要问题。本文会涉及常见的代码优化方法,性能优化工具的使用以及如何诊断代码的性能瓶颈等内容,希望可以给 Python 开发人员一定的参考。...

python的类方法和静态方法

本文实例讲述了python的类方法和静态方法。分享给大家供大家参考。具体分析如下: python没有和C++中static关键字,它的静态方法是怎样的呢?还有其它语言中少有的类方法又是神...