import com.jcraft.jsch.*;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Properties;
public class OperateLinux {
private static Session session = null;
private static int timeout = 60000;
private static ChannelExec channelExec;
/**
* 连接远程服务器
* @param hostname 为远程linux 服务器
* @param username linux用户名
* @param password linux登录密码
* @param port linux 登录端口号
*/
public static void connect(String hostname, String username, String password, int port) throws Exception{
System.out.println("尝试连接到...host:"+hostname+", 登录名为:"+username+",端口号为:"+port);
Channel channel = null;
JSch jsch = new JSch(); // 创建jsch 对象
//连接服务器,如果端口小于等于0,采用默认端口,如果大于0,使用指定的端口
if(port <=0)
{
//连接服务器,采用默认端口
session = jsch.getSession(username,hostname);
} else {
//采用指定的端口连接服务器
session = jsch.getSession(username, hostname, port);
}
//如果服务器连不上,则抛出异常
if(session == null)
{
throw new Exception("session is nuoll");
}
//设置登录主机的密码
session.setPassword(password);
//设置第一次登录的时候的提示,可选择(ask | yes | no)
// session.setConfig("StrictHostKeyChecking", "no");
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking","no");
session.setConfig(sshConfig);
// 设置登陆超时时间ms
session.setTimeout(timeout);
session.connect();
System.out.println("Session connected.");
System.out.println("Opening Channel.");
}
/**
* 在远程服务器上执行命令
* @param cmd 要执行的命令字符串
* @param charset 编码
* @throws Exception
*/
public static void execute(String cmd, String charset) throws Exception{
channelExec = (ChannelExec) session.openChannel("exec");
channelExec.setCommand(cmd);
channelExec.setInputStream(null);
channelExec.setErrStream(System.err);
channelExec.connect();
InputStream in = channelExec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));
String buf = null;
while ((buf = reader.readLine()) != null){
System.out.println(buf);
}
reader.close();
channelExec.disconnect();
}
public static void main(String[] args) {
//测试代码
try {
System.out.println("连接linux 服务器:");
connect("10.185.47.202","vmware","VMware123!",22);
System.out.println("服务器已连接,准备使用mkdir创建文件夹:why");
execute("mkdir why","UTF-8");
System.out.println("why文件夹已创建,ls显示创建的文件");
execute("ls","UTF-8");
System.out.println("准备使用linux命令rm删除文件夹why");
execute("rm -rf why","UTF-8");
System.out.println("文件夹why 已通过命令删除");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}