Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Sudo {
- private static final int timeout = 10000;
- public static String sudo_pass = "john123";
- public static void main(String[] arg) {
- try {
- JSch jsch = new JSch();
- String user = "john";
- String host = "192.168.56.103";
- Session session = jsch.getSession(user, host, 22);
- UserInfo ui = new MyUserInfo();
- session.setUserInfo(ui);
- session.connect(timeout);
- String command = "sudo poweroff";
- ChannelExec channel = (ChannelExec) session.openChannel("exec");
- // man sudo
- // -S The -S (stdin) option causes sudo to read the password from the
- // standard input instead of the terminal device.
- // -p The -p (prompt) option allows you to override the default
- // password prompt and use a custom one.
- channel.setCommand("sudo -S -p '' " + command);
- channel.setPty(true);
- InputStream in = channel.getInputStream();
- OutputStream out = channel.getOutputStream();
- channel.setErrStream(System.err);
- channel.connect();
- out.write((sudo_pass + "n").getBytes());
- out.flush();
- 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()) {
- 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);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement