如何使用 Jsch exec 在服务器内的文件上写入
How to write on a file inside a server using Jsch exec
我尝试了一些命令,例如
echo "Your text here" | ssh hostname 'cat >> output.txt'
但是没用。
如何使用此 exec 代码或我将放入 String 命令的 ssh 命令写入服务器内的文件。
public class TestWrite{
private static final String user = "username here";
private static final String host = "host here";
private static final String password = "pass here";
public static void main(String[] arg){
try{
JSch jsch=new JSch();
Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
String command = "Command here";
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
System.out.print(new String(tmp, 0, i));
}
if(channel.isClosed()){
if(in.available()>0) continue;
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
}
catch(Exception e){
System.out.println(e);
}
}
}
尝试如下命令:
ssh hostname 'echo "Your text here" >> output.txt'
您可以使用
写入文件
echo "your text here" > file
你不需要 ssh
因为 Jsch 取代了它。
我尝试了一些命令,例如
echo "Your text here" | ssh hostname 'cat >> output.txt'
但是没用。
如何使用此 exec 代码或我将放入 String 命令的 ssh 命令写入服务器内的文件。
public class TestWrite{
private static final String user = "username here";
private static final String host = "host here";
private static final String password = "pass here";
public static void main(String[] arg){
try{
JSch jsch=new JSch();
Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
String command = "Command here";
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
System.out.print(new String(tmp, 0, i));
}
if(channel.isClosed()){
if(in.available()>0) continue;
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
}
catch(Exception e){
System.out.println(e);
}
}
}
尝试如下命令:
ssh hostname 'echo "Your text here" >> output.txt'
您可以使用
写入文件echo "your text here" > file
你不需要 ssh
因为 Jsch 取代了它。