你可以使用Java中的SSH庫(kù)來連接遠(yuǎn)程服務(wù)器并執(zhí)行shell命令。下面是一個(gè)簡(jiǎn)單的示例代碼:文章來源:http://www.zghlxwxcb.cn/news/detail-809269.html
import com.jcraft.jsch.*;
public class SSHExample {
public static void main(String[] args) {
String host = "your_host";
String username = "your_username";
String password = "your_password";
int port = 22;
try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand("your_shell_command");
channel.connect();
InputStream in = channel.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
channel.disconnect();
session.disconnect();
} catch (JSchException | IOException e) {
e.printStackTrace();
}
}
}
請(qǐng)注意替換your_host
,your_username
,your_password
和your_shell_command
為實(shí)際的遠(yuǎn)程服務(wù)器信息和要執(zhí)行的shell命令。該示例代碼使用JSch庫(kù)來建立SSH連接并執(zhí)行命令。文章來源地址http://www.zghlxwxcb.cn/news/detail-809269.html
到了這里,關(guān)于java實(shí)現(xiàn)連接遠(yuǎn)程服務(wù)器,并可以執(zhí)行shell命令的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!