java jsch 切换用户并输入密码 ,Java JSch在远程机器上更改用户并执行命令
时间: 2024-02-03 08:12:09 浏览: 174
Java中通过jsch来连接远程服务器执行linux命令
5星 · 资源好评率100%
使用Java JSch可以在远程机器上更改用户并执行命令,可以通过以下步骤实现:
1. 创建JSch对象,用于连接远程机器。
```java
JSch jsch = new JSch();
```
2. 使用JSch对象创建Session对象,并设置用户名、主机名和端口号,连接远程机器。
```java
String user = "username";
String host = "hostname";
int port = 22;
Session session = jsch.getSession(user, host, port);
```
3. 设置Session对象的密码,并连接远程机器。
```java
String password = "password";
session.setPassword(password);
session.connect();
```
4. 使用Session对象创建Channel对象,并设置类型为"exec",表示执行命令。
```java
Channel channel = session.openChannel("exec");
```
5. 设置Channel对象要执行的命令。
```java
String command = "sudo -S -p '' su - newuser";
((ChannelExec) channel).setCommand(command);
```
6. 执行命令前,需要输入新用户的密码。使用OutputStream向Channel对象传递密码。
```java
OutputStream outputStream = channel.getOutputStream();
String newuserPassword = "newuserpassword\n";
outputStream.write(newuserPassword.getBytes());
outputStream.flush();
```
7. 执行命令,并获取命令执行结果。
```java
channel.connect();
InputStream inputStream = channel.getInputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, len));
}
```
8. 关闭连接。
```java
channel.disconnect();
session.disconnect();
```
完整代码示例:
```java
import com.jcraft.jsch.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class JSchDemo {
public static void main(String[] args) {
JSch jsch = new JSch();
String user = "username";
String host = "hostname";
int port = 22;
Session session = null;
try {
session = jsch.getSession(user, host, port);
String password = "password";
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("exec");
String command = "sudo -S -p '' su - newuser";
((ChannelExec) channel).setCommand(command);
OutputStream outputStream = channel.getOutputStream();
String newuserPassword = "newuserpassword\n";
outputStream.write(newuserPassword.getBytes());
outputStream.flush();
channel.connect();
InputStream inputStream = channel.getInputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, len));
}
channel.disconnect();
session.disconnect();
} catch (JSchException | IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文