Java 如何以字符串形式获取JSCHshell命令输出
我正在使用JSCH-SSH库在“shell”通道中执行命令,但找不到方法 要做两件事:- 1) 如何确定该命令是否在远程unix box上完全执行 2) 如何以字符串形式捕获命令输出,而不是在System.out控制台上打印它 下面是我的代码片段,它可以很好地在system.out上显示shell命令输出 注意:我不想使用“exec”通道,因为它为每个命令启动一个新进程,并且不记得导出的“session”变量。我必须使用“shell”频道 下面是我的代码片段。非常感谢您的帮助。谢谢您抽出时间Java 如何以字符串形式获取JSCHshell命令输出,java,ssh,jsch,Java,Ssh,Jsch,我正在使用JSCH-SSH库在“shell”通道中执行命令,但找不到方法 要做两件事:- 1) 如何确定该命令是否在远程unix box上完全执行 2) 如何以字符串形式捕获命令输出,而不是在System.out控制台上打印它 下面是我的代码片段,它可以很好地在system.out上显示shell命令输出 注意:我不想使用“exec”通道,因为它为每个命令启动一个新进程,并且不记得导出的“session”变量。我必须使用“shell”频道 下面是我的代码片段。非常感谢您的帮助。谢谢您抽出时间 t
try{
String commandToRun = "ls /tmp/*.log \n";
if(channel.isClosed())
channel=session.openChannel("shell");
byte[] bytes = commandToRun.getBytes();
ByteArrayInputStream bais=new ByteArrayInputStream(bytes);
channel.setInputStream(bais);
InputStream ins=channel.getInputStream();
channel.connect();
channel.setOutputStream(System.out);//This prints on console. Need 2 capture in String somehow?
//in-efficient way to allow command to execute completely on remote Unix machine
//DO NOT know a better way, to know when command is executed completely
Thread.sleep(5000L);
}
catch(Exception e){
System.out.println("Exception in executeCommand() --->"+ e.getMessage());
e.printStackTrace();
}
对于2)您可以使用ByteArrayOutputStream
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
channel.setOutputStream(baos);
然后从新字符串(baos.toByteArray())创建新字符串
对于1,您是否尝试在命令末尾使用2>&1
String commandToRun = "ls /tmp/*.log 2>&1 \n";
对于2)您可以使用ByteArrayOutputStream
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
channel.setOutputStream(baos);
然后从新字符串(baos.toByteArray())创建新字符串
对于1,您是否尝试在命令末尾使用2>&1
String commandToRun = "ls /tmp/*.log 2>&1 \n";
OP可能不再需要我的解决方案,但任何正在搜索解决方案以满足这两种条件的人1)等待命令在远程机器上完成;2)将输出捕获为字符串;您可以尝试以下方法:
public class SshConnectionManager {
private static Session session;
private static ChannelShell channel;
private static String username = "";
private static String password = "";
private static String hostname = "";
private static Session getSession(){
if(session == null || !session.isConnected()){
session = connect(hostname,username,password);
}
return session;
}
private static Channel getChannel(){
if(channel == null || !channel.isConnected()){
try{
channel = (ChannelShell)getSession().openChannel("shell");
channel.connect();
}catch(Exception e){
System.out.println("Error while opening channel: "+ e);
}
}
return channel;
}
private static Session connect(String hostname, String username, String password){
JSch jSch = new JSch();
try {
session = jSch.getSession(username, hostname, 22);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(password);
System.out.println("Connecting SSH to " + hostname + " - Please wait for few seconds... ");
session.connect();
System.out.println("Connected!");
}catch(Exception e){
System.out.println("An error occurred while connecting to "+hostname+": "+e);
}
return session;
}
private static void executeCommands(List<String> commands){
try{
Channel channel=getChannel();
System.out.println("Sending commands...");
sendCommands(channel, commands);
readChannelOutput(channel);
System.out.println("Finished sending commands!");
}catch(Exception e){
System.out.println("An error ocurred during executeCommands: "+e);
}
}
private static void sendCommands(Channel channel, List<String> commands){
try{
PrintStream out = new PrintStream(channel.getOutputStream());
out.println("#!/bin/bash");
for(String command : commands){
out.println(command);
}
out.println("exit");
out.flush();
}catch(Exception e){
System.out.println("Error while sending commands: "+ e);
}
}
private static void readChannelOutput(Channel channel){
byte[] buffer = new byte[1024];
try{
InputStream in = channel.getInputStream();
String line = "";
while (true){
while (in.available() > 0) {
int i = in.read(buffer, 0, 1024);
if (i < 0) {
break;
}
line = new String(buffer, 0, i);
System.out.println(line);
}
if(line.contains("logout")){
break;
}
if (channel.isClosed()){
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee){}
}
}catch(Exception e){
System.out.println("Error while reading channel output: "+ e);
}
}
public static void close(){
channel.disconnect();
session.disconnect();
System.out.println("Disconnected channel and session");
}
public static void main(String[] args){
List<String> commands = new ArrayList<String>();
commands.add("ls -l");
executeCommands(commands);
close();
}
}
公共类SshConnectionManager{
非公开静态会议;
专用静态信道;
私有静态字符串username=“”;
私有静态字符串密码=”;
私有静态字符串hostname=“”;
私有静态会话getSession(){
if(session==null | |!session.isConnected()){
会话=连接(主机名、用户名、密码);
}
返回会议;
}
专用静态通道getChannel(){
if(channel==null | |!channel.isConnected()){
试一试{
channel=(ChannelShell)getSession().openChannel(“shell”);
channel.connect();
}捕获(例外e){
System.out.println(“打开通道时出错:+e”);
}
}
返回通道;
}
专用静态会话连接(字符串主机名、字符串用户名、字符串密码){
JSch JSch=新的JSch();
试一试{
session=jSch.getSession(用户名、主机名、22);
属性配置=新属性();
配置放置(“检查”、“否”);
session.setConfig(config);
session.setPassword(密码);
System.out.println(“将SSH连接到“+hostname+”-请等待几秒钟…”);
session.connect();
System.out.println(“已连接!”);
}捕获(例外e){
System.out.println(“连接到“+hostname+”:“+e”时出错);
}
返回会议;
}
私有静态void executeCommands(列表命令){
试一试{
Channel=getChannel();
System.out.println(“发送命令…”);
发送命令(通道、命令);
读通道输出(通道);
System.out.println(“发送命令完成!”);
}捕获(例外e){
System.out.println(“在执行命令时发生错误:”+e);
}
}
专用静态无效发送命令(通道、通道、列表命令){
试一试{
PrintStream out=新的PrintStream(channel.getOutputStream());
out.println(“#!/bin/bash”);
用于(字符串命令:命令){
out.println(命令);
}
out.println(“退出”);
out.flush();
}捕获(例外e){
System.out.println(“发送命令时出错:“+e”);
}
}
专用静态无效读通道输出(通道){
字节[]缓冲区=新字节[1024];
试一试{
InputStream in=channel.getInputStream();
字符串行=”;
while(true){
while(in.available()>0){
inti=in.read(缓冲区,0,1024);
if(i<0){
打破
}
行=新字符串(缓冲区,0,i);
系统输出打印项次(行);
}
如果(第行包含(“注销”)){
打破
}
if(channel.isClosed()){
打破
}
试一试{
睡眠(1000);
}捕获(异常ee){}
}
}捕获(例外e){
System.out.println(“读取通道输出时出错:+e”);
}
}
公共静态无效关闭(){
通道断开();
session.disconnect();
System.out.println(“断开的通道和会话”);
}
公共静态void main(字符串[]args){
List命令=new ArrayList();
命令。添加(“ls-l”);
executeCommands(命令);
close();
}
}
如果您需要一次发送多个命令,并保持通道开放以便以后重新使用,此解决方案也很有用。OP可能不再需要我的解决方案,但正在搜索解决方案以涵盖这两种情况的任何其他人1)等待命令在远程计算机上完成;2)将输出捕获为字符串;您可以尝试以下方法:
public class SshConnectionManager {
private static Session session;
private static ChannelShell channel;
private static String username = "";
private static String password = "";
private static String hostname = "";
private static Session getSession(){
if(session == null || !session.isConnected()){
session = connect(hostname,username,password);
}
return session;
}
private static Channel getChannel(){
if(channel == null || !channel.isConnected()){
try{
channel = (ChannelShell)getSession().openChannel("shell");
channel.connect();
}catch(Exception e){
System.out.println("Error while opening channel: "+ e);
}
}
return channel;
}
private static Session connect(String hostname, String username, String password){
JSch jSch = new JSch();
try {
session = jSch.getSession(username, hostname, 22);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(password);
System.out.println("Connecting SSH to " + hostname + " - Please wait for few seconds... ");
session.connect();
System.out.println("Connected!");
}catch(Exception e){
System.out.println("An error occurred while connecting to "+hostname+": "+e);
}
return session;
}
private static void executeCommands(List<String> commands){
try{
Channel channel=getChannel();
System.out.println("Sending commands...");
sendCommands(channel, commands);
readChannelOutput(channel);
System.out.println("Finished sending commands!");
}catch(Exception e){
System.out.println("An error ocurred during executeCommands: "+e);
}
}
private static void sendCommands(Channel channel, List<String> commands){
try{
PrintStream out = new PrintStream(channel.getOutputStream());
out.println("#!/bin/bash");
for(String command : commands){
out.println(command);
}
out.println("exit");
out.flush();
}catch(Exception e){
System.out.println("Error while sending commands: "+ e);
}
}
private static void readChannelOutput(Channel channel){
byte[] buffer = new byte[1024];
try{
InputStream in = channel.getInputStream();
String line = "";
while (true){
while (in.available() > 0) {
int i = in.read(buffer, 0, 1024);
if (i < 0) {
break;
}
line = new String(buffer, 0, i);
System.out.println(line);
}
if(line.contains("logout")){
break;
}
if (channel.isClosed()){
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee){}
}
}catch(Exception e){
System.out.println("Error while reading channel output: "+ e);
}
}
public static void close(){
channel.disconnect();
session.disconnect();
System.out.println("Disconnected channel and session");
}
public static void main(String[] args){
List<String> commands = new ArrayList<String>();
commands.add("ls -l");
executeCommands(commands);
close();
}
}
公共类SshConnectionManager{
非公开静态会议;
专用静态信道;
私有静态字符串username=“”;
私有静态字符串密码=”;
私有静态字符串hostname=“”;
私有静态会话getSession(){
if(session==null | |!session.isConnected()){
会话=连接(主机名、用户名、密码);
}
返回会议;
}
专用静态通道getChannel(){
if(channel==null | |!channel.isConnected()){
试一试{
channel=(ChannelShell)getSession().openChannel(“shell”);
channel.connect();
}捕获(例外e){
System.out.println(“打开通道时出错:+e”);
}
}
返回通道;
}
专用静态会话连接(字符串主机名、字符串用户名、字符串密码){
JSch JSch=新的JSch();
试一试{
session=jSch.getSession(用户名、主机名、22);
属性c