欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 调用python实现shell脚本上传到远端服务器,并执行这个shell脚本。

程序员文章站 2022-06-30 21:26:11
java 调用python实现shell脚本上传到远端服务器,并执行这个shell脚本。1.java代码 备注:调用python传人第一个参数一定是自己python的位置,否则使用idea的默认python,可能输出为null.import java.io.IOException;import java.io.InputStreamReader;import java.io.LineNumberReader;public class RuntimeFunction { public...

java 调用python实现shell脚本上传到远端服务器,并执行这个shell脚本。

1.java代码 备注:调用python传人第一个参数一定是自己python的位置,否则使用idea的默认python,可能输出为null.

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

public class RuntimeFunction {
    public static void main(String[] args) {
        String result="";
        Process proc;
        try {
            //  python /Users/zx/Sites/sshUserfile.py 'sh /Users/zx/Sites/test.sh'
            String [] args1=new String[]{"/Library/Frameworks/Python.framework/Versions/3.7/bin/python3","/Users/zx/Sites/sshUserfile.py","sh /Users/zx/Sites/test.sh"};
            proc=Runtime.getRuntime().exec(args1);
            InputStreamReader ir=new InputStreamReader(proc.getInputStream());
            LineNumberReader input=new LineNumberReader(ir);
            while((result=input.readLine())!=null){
                System.out.println(result);
            }

            input.close();
            ir.close();
            proc.waitFor();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

2.sshUserfile.py 注意python可以使用python3,如果使用2需要导入对应的包。

#coding:utf-8
 
import sys
import paramiko
import threading
import time
 
def getConnection(ip,username,password,command,port = 22): 
     #实例化对象
     print("in getConnection")
     ssh = paramiko.SSHClient()
     policy = paramiko.AutoAddPolicy()
     ssh.set_missing_host_key_policy(policy)          #连接
     ssh.connect(
         hostname = ip,  # 服务器的ip
         port = port,  # 服务器的端口
         username = username,  # 服务器的用户名
         password = password  # 用户名对应的密码
     )      #执行
     stdin, stdout, stderr = ssh.exec_command(command)
 
     result = stdout.read().decode()
 
     error = stderr.read().decode()
 
     print("+++++++++++++++++++++++start++++++++++++++++++++")
     print("[connect success] | ip : %s" % ip)
     print("result: \n %s"%result)
     if error != " ":
         print("error: \n %s"%error)
     print("+++++++++++++++++++++++done++++++++++++++++++++")
 
     ssh.close()

#读取文件内容
def loadDatadet(infile):
    f=open(infile,'r')
    sourceInLine=f.readlines()
    dataset=[] 
    for line in sourceInLine:
        temp1=line.strip('\n')
        temp2=temp1.split('\t')
        dataset.append(temp2)
    return dataset

#上传文件到远程主机
def uploadFile(ip,username,password,sourceDestination,targetDestination,port=22):
   t = paramiko.Transport((ip,port))
   try:
    t.connect(username=username,password=password)
    sftp = paramiko.SFTPClient.from_transport(t)
    #sftp.get('/pythonShare/ssh.py','ssh.py.bak')#下载
    sftp.put(sourceDestination,targetDestination)#上传 
   except Exception as e:
    print("上传连接出错ip:%s,port:%s,username:%s,sourceDestination:%s,targetDestination:%s"%(ip,port,username,sourceDestination,targetDestination));
    print("Error:",e)
   else:
    print("上传成功ip:%s,port:%s,username:%s"%(ip,port,username));
   finally:
    t.close()

 #我们采用多线程
def main(host_list,command):
     print("in main:command:%s",command)
     try:
      thread_list = []
      for list in host_list:
         line=list.split()
         print (line)
         print("hello main")
         ip=line[0].strip()
         username=line[1].strip()
         password=line[2].strip()
         thread = threading.Thread(target = getConnection, args = (ip,username,password,command))
         thread_list.append(thread)
      for t in thread_list:
         t.start()
      for t in thread_list:
         t.join()
     except:
         print("出错");

#采用多线程
def mainUpload(host_list,sourceDst,targetDst,command):
     try:
      thread_list_upload = []
      for list in host_list:
         line=list.split()
         print (line)
         ip=line[0].strip()
         username=line[1].strip()
         password=line[2].strip()
         thread_upload = threading.Thread(target = uploadFile, args = (ip,username,password,sourceDst,targetDst))
         thread = threading.Thread(target = getConnection, args = (ip,username,password,command))
         thread_list_upload.append(thread_upload)
         thread_list_upload.append(thread)
      for tu in thread_list_upload:
         tu.start()
         tu.join()
      #for tu in thread_list_upload:
      #   tu.join()
     except Exception as e:
         print("mainupload出错:",e);
 
if __name__ == "__main__":
     infile='/users/zx/Sites/serverHost.txt'
     hosts=open(infile)
     command = sys.argv[1]
     mainUpload(hosts,'/Users/zx/test.sh','/Users/zx/Sites/test.sh',command)
     #main(hosts,command)

3. serverHost.txt 格式:ip 用户名  密码

192:Sites zx$ cat serverHost.txt
127.0.0.1 zx 123456
127.0.0.1 tomcat 123456
127.0.0.1 zx 123456


192:Sites zx$ cat test.sh 
#!/bin/bash
echo "hello world"
df -ih
/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/bin/java -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:50942,suspend=y,server=n -javaagent:/Users/zx/Library/Caches/IntelliJIdea2018.3/captureAgent/debugger-agent.jar -Dfile.encoding=UTF-8 -classpath "/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/lib/ant-javafx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/lib/dt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/lib/javafx-mx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/lib/jconsole.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/lib/packager.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/lib/sa-jdi.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/lib/tools.jar:/Users/zx/Downloads/leetcode/leetcodetest/out/production/leetcodetest:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar" bookTest.RuntimeFunction
Connected to the target VM, address: '127.0.0.1:50942', transport: 'socket'
['127.0.0.1', 'zx', '123456']
['127.0.0.1', 'tomcat', '123456']
['127.0.0.1', 'zx', '123456']
上传成功ip:127.0.0.1,port:22,username:zhaoxing
in getConnection
+++++++++++++++++++++++start++++++++++++++++++++
[connect success] | ip : 127.0.0.1
result: 
 hello world
Filesystem      Size   Used  Avail Capacity iused               ifree %iused  Mounted on
/dev/disk1s1   233Gi  108Gi  124Gi    47% 1031254 9223372036853744553    0%   /
devfs          184Ki  184Ki    0Bi   100%     636                   0  100%   /dev
/dev/disk1s4   233Gi  1.0Gi  124Gi     1%       1 9223372036854775806    0%   /private/var/vm
map -hosts       0Bi    0Bi    0Bi   100%       0                   0  100%   /net
map auto_home    0Bi    0Bi    0Bi   100%       0                   0  100%   /home

error: 
 
+++++++++++++++++++++++done++++++++++++++++++++

//备注:没有把三次都列出来。就粘贴出一次

 

本文地址:https://blog.csdn.net/ZHAOXING_ME/article/details/109830019