- 实际工作场景中有时候会遇到需要切换其他用户来执行多条linux命令,但是测试发现无论是通过 ";","&&","||"都没有办法直接切换用户来执行命令。
- 以db2为例,有些严格的环境会不能通过数据库工具远程登陆db2,只能通过shell命令执行数据库的查询工作。
# 可以工作
sudo -i -u dbusr
db2 connect to db
# 不能工作
sudo -i -u dbusr; db2 connect to db
- sshxcute的ExecCommand方法只能执行一条命令,且无法记录上下文关系。所以我们换一个思路来实现这个功能。
#记录当前目录
currentPath=`pwd`;
#将需要执行的命令写入到临时文件中
echo "db2 connect to db" >> tmpCmd-2018-08-07-05-01-15.sh;
echo "pwd" >> tmpCmd-2018-08-07-05-01-15.sh;
#为该临时文件添加其他用户可以访问权限
chmod 777 tmpCmd-2018-08-07-05-01-15.sh;
#切换用户用户并执行该文件
sudo -i -u dbusr ${currentPath}/tmpCmd-2018-08-07-05-01-15.sh;
#打印文件内容并删除该临时文件
cat tmpCmd-2018-08-07-05-01-15.sh;
rm tmpCmd-2018-08-07-05-01-15.sh
cpublic class SwitchUserTask extends CustomTask {
private static String tempCmdFile = "tmpCmd.sh";
protected String command = "";
private String[] args;
public SwitchUserTask(String user, String... args) {
this.args = args;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
tempCmdFile = FilenameUtils.getBaseName(tempCmdFile) + "-" + df.format(new Date()) + "." + FilenameUtils.getExtension(tempCmdFile);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < args.length; i++) {
sb.append("echo \"" + args[i].replace("\"", "\\\"") + "\" >> " + tempCmdFile + ";");
}
this.command = "currentPath=`pwd`;rm " + tempCmdFile + ";" +
sb.toString() +
"chmod 777 " + tempCmdFile + ";" +
"sudo -i -u " + user + " ${currentPath}/" + tempCmdFile + ";" +
"cat " + tempCmdFile + ";" +
"rm " + tempCmdFile + ";";
}
public Boolean checkStdOut(String stdout) {
Iterator<String> iter = err_sysout_keyword_list.iterator();
while (iter.hasNext()) {
if (stdout.contains(iter.next())) {
return false;
}
}
return true;
}
public Boolean checkExitCode(int exitCode) {
if (exitCode == 0)
return true;
else
return false;
}
public String getCommand() {
return command;
}
public List<String> getInputCommands(){
return Arrays.asList(args);
}
public String getInfo() {
return "Exec command " + getCommand();
}
}
CustomTask task = new SwitchUserTask("dbusr", "db2 connect to dbname", "pwd");
Result result = ssh.exec(task);
logger.info("Command is [{}]", task.getCommand());
logger.info("Input commands: {}"+((SwitchUserTask) task).getInputCommands());