PsExec和Java连接到远程Windows服务器
问题描述:
我有一个需求,我需要从另一台个人Windows机器连接到Windows服务器。我还需要能够将CD放入远程计算机上的特定文件夹中,获取该文件夹中的文件列表并检查该文件夹中是否存在文件。当我开始研究这个,我可以理解,有两种选择:PsExec和Java连接到远程Windows服务器
- 对Windows Server和使用客户端上安装OpenSSH的像JSch连接 - 我的团队红外线可能会或可能不会批准这一请求。
- 使用PsExec进行连接并做类似的事情 - 这里是我能够连接的位置,但无法弄清如何将CD放入目录并获取任何文件夹中的文件列表。
以下是我在代码方面:
private static void authenticateAndExecute() {
String psCommand = PATH_TO_PSEXEC + "\\PsExec.exe \\\\" + "testdev19" + " -u " + "userName"
+ " -p " + "password";
psCommand = psCommand + " " + "cmd cd c:\\destdir" + " dir ";
String[] cmd = new String[5];
cmd[0] = "cmd.exe";
cmd[1] = "/C";
cmd[2] = psCommand;
cmd[3] = "";
cmd[4] = "";
// Run remote command
Process p = null;
try {
p = Runtime.getRuntime().exec(cmd, null);
System.out.println("Connected..." + p.getOutputStream());
InputStream is = p.getInputStream();
OutputStream os = p.getOutputStream();
InputStream es = p.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
BufferedReader errReader = new BufferedReader(new InputStreamReader(es));
String line;
// Read STDOUT into a buffer.
while ((line = errReader.readLine()) != null) {
System.out.println(line);
}
// If no STDOUT check STDERR.
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// Wait for the process to end.
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (p != null) {
p.destroy();
}
}
}
所有我在此之后运行看到的是,过程已经为0的返回码结束了我想看到的名单目标目录中的文件。这甚至有可能使用PsExec或者我走错了路?
任何帮助表示赞赏...
答
请看看:
https://www.ibm.com/developerworks/community/blogs/738b7897-cd38-4f24-9f05-48dd69116837/entry/programmatically_connecting_to_remote_systems2?lang=en
可能解决您的问题
+0
请在帖子中提供答案的详细信息,而不是仅提供一个链接。 – lofihelsinki
答
String psCommand = "<path_of_psexec>/psexec.exe \\\\"+currentServerHostname + " -u " + currentServerUser + " -p " + currentServerPass;
psCommand = psCommand + " " + commandToRunOnRemoteMachine + " " + parameters;
String[] cmd = new String[5];
cmd[0]="cmd.exe";
cmd[1]="/C";
cmd[2]=psCommand;
cmd[3]="";
cmd[4]="";
// Run remote command
File f = new File(getCurrentWorkingDirectory() + "\\lib");
Process p = Runtime.getRuntime().exec(cmd,null,f);
你不能使用文件共享? '\\ testdev19 \ c $ \ destdir'应该显示该文件夹中的文件。 –
感谢Harry的建议,但不幸的是,我需要在500多台服务器上完成这项工作,而不是所有的服务器所有者都允许共享一个文件夹。这就是原因,我想以编程方式使用Java来做这件事,因为我在那种语言中更加舒适! – Prashanth
仅供参考,根据我的经验,如果文件共享关闭,psexec也不起作用。可能有边缘情况,我不确定细节。 (但是作为一个系统管理员我自己,我宁愿让某人访问一个适当受限的文件共享,而不是让他们通过psexec访问管理员!) –