使用 python 脚本升级 linux

Upgrade linux with a python script

我想用 python 脚本升级我的 linux 系统。但我不知道如何向控制台发送 Y 或 Enter。

这是我的代码:

sudo_password = 'password'
command = 'apt-get update'
os.system('echo %s|sudo -S %s' % (sudo_password, command))
command = 'apt-get upgrade'
os.system('echo %s|sudo -S %s' % (sudo_password, command))

编辑:

我想 运行 脚本自动化,因此我不想使用 raw_input() 或 input()。

使用raw_input函数

例如

user_input = raw_input('Enter Y ')

或者,您可以将 -y 参数添加到 apt-get 命令中。像这样:

...
command = 'apt-get upgrade -y'
...

如果您只想对所有 apt-get 提示回答 'y',请考虑通过 yes bash 命令管道命令。

未测试(您应该测试):

command = 'apt-get update|yes'
os.system('echo %s|sudo -S %s' % (sudo_password, command))
command = 'apt-get upgrade|yes'
os.system('echo %s|sudo -S %s' % (sudo_password, command))

yes 手册页描述说:

Repeatedly output a line with all specified STRING(s), or 'y'.