简体   繁体   English

如何在 cronjob 脚本中提供用户输入

[英]How to give user input in cronjob script

I have a run a script in cronjob.我在 cronjob 中运行了一个脚本。 But that script is taking some user input.但是该脚本正在接受一些用户输入。

How can I handle such case?我该如何处理这种情况?

If it's taking the input from stdin, make another script that will call your script with a pipe or a redirect.如果它从 stdin 获取输入,请制作另一个脚本,该脚本将使用管道或重定向来调用您的脚本。

#!/bin/sh
/foo/bar/my_command < my_input

You can also launch it as a shell command in your crontab:您还可以在 crontab 中将其作为 shell 命令启动:

0 * * * * /bin/sh -c "/foo/bar/my_command < my_input"
  1. Modify the script so it does not need user input.修改脚本,使其不需要用户输入。

  2. Feed the script its required input from a file, via < .通过< ,从文件中为脚本提供所需的输入。

Just in case the "expected user input" is, by any chance, a password: Do not use option 2. Editing access authentification into a crontab job is various flavors of dangerous.以防万一“预期的用户输入”是密码:不要使用选项 2。将访问身份验证编辑到 crontab 作业中是各种危险的。

PS: That warning above is also true if you're thinking about expect , as suggested by mvp. PS:如 mvp 所建议的expect ,如果您正在考虑expect ,则上述警告也是正确的。 It is basically the equivalent of writing down your password on a post-it and sticking it to your monitor: Easy, convenient, and not secure at all.这基本上相当于在便利贴上写下您的密码并将其贴在您的显示器上:简单、方便,但根本不安全。

You can use expect to simulate manual user input into your script.您可以使用expect来模拟用户手动输入到您的脚本中。 This works even if your script does not accept redirection (possible if it needs to enter passwords).即使您的脚本不接受重定向(如果需要输入密码,则可能),这也有效。

In practice, I found that Perl Expect is much easier to write script for compared to bare expect .在实践中,我发现与裸expect相比,Perl Expect更容易编写脚本。

如果您只需要在脚本中确认(是),crontab 可能如下所示:

0 * * * * /bin/sh -c "yes | /foo/bar/my_command"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM