python 使用 linux shell sudo

版权声明:原创文章 by LynnChan https://blog.csdn.net/ccchen706/article/details/72627265

需要在python下执行文件权限更改,发现普通的交互方式 如:

	os.system('echo %s|sudo -S %s' % (sudoPassword, command))
	Popen("sudo chmod 777 /dev/%s" % (ser), 'w').write('***')

      

等都会报错如下,无法执行sudo等指令.

	没有终端存在,且未指定 askpass 程序

可使用pexpect模块来完成上述功能.代码如下:

        shell_cmd = "sudo chmod 777 "+devicestr
        child = pexpect.spawn(shell_cmd)
        index = child.expect(['password',pexpect.EOF,pexpect.TIMEOUT])
        if index == 0:
            child.sendline(passwd)




猜你喜欢

转载自blog.csdn.net/ccchen706/article/details/72627265