package tools;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.session.ClientSession;
public class PscpUtil {
public static void pscp_Upload(String username,String password,String port,String host,String remote,String local) throws IOException {
String err=new String();
String str=new String();
System.out.println("正在上传......");
Process process = Runtime.getRuntime().exec(
"cmd /c pscp -r -l "+username+" -pw "+password+" "+local+" -P "+port+" "+host+":"+remote);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
BufferedReader errReader = new BufferedReader(
new InputStreamReader(process.getErrorStream()));
while ((err = errReader.readLine()) != null)
System.out.println(err);
while ((str = bufferedReader.readLine()) != null)
System.out.println(str);
process.destroy();
}
public static void pscp_Download(String username,String password,String port,String host,String remote,String local) throws IOException {
String err=new String();
String str=new String();
Process process = Runtime.getRuntime().exec(
"cmd /c pscp -r -l "+username+" -pw "+password+" -P "+port+" "+host+":"+remote+" "+local);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
BufferedReader errReader = new BufferedReader(
new InputStreamReader(process.getErrorStream()));
while ((err = errReader.readLine()) != null)
System.out.println(err);
while ((str = bufferedReader.readLine()) != null)
System.out.println(str);
process.destroy();
}
public static void LinuxCmd(String host, String username, String password, String command) throws Exception {
/*
创建命令
*/
// 创建 SSH客户端
SshClient client = SshClient.setUpDefaultClient();
// 启动 SSH客户端
client.start();
// 通过主机IP、端口和用户名,连接主机,获取Session
ClientSession session = client.connect(username, host, 22).verify().getSession();
// 给Session添加密码
session.addPasswordIdentity(password);
// 校验用户名和密码的有效性
boolean isSuccess = session.auth().verify().isSuccess();
// 认证成功
if (isSuccess) {
String s = session.executeRemoteCommand(command);// 执行命令
System.out.println(s);
client.stop();
}else {
throw new Exception("共享服务器连接失败!!!");
}
}
}
如pscp_Upload和pscp_Download方法所示,提供Linux服务器的ip地址,端口号,用户名,密码,本地文件地址与远程文件地址即可实现文件传输。
如LinuxCmd方法所示,提供ip地址,用户名,密码,以及需要执行的linux命令,
创建并启动SSH客户端
SshClient client = SshClient.setUpDefaultClient();
client.start();
通过主机IP、端口和用户名,连接主机,获取Session,并设置密码
ClientSession session = client.connect(username, host, 22).verify().getSession();
// 给Session添加密码
session.addPasswordIdentity(password);
校验密码有效性
// 校验用户名和密码的有效性
boolean isSuccess = session.auth().verify().isSuccess();
认证成功,则执行Linux指令。
// 认证成功
if (isSuccess) {
String s = session.executeRemoteCommand(command);// 执行命令
System.out.println(s);
client.stop();
}else {
throw new Exception("共享服务器连接失败!!!");
}
软件下载pscp软件下载https://download.youkuaiyun.com/download/qq_43210879/86583757