Python virtualenv:创建独立python环境

#安装virtualenv包
[root@izwz9ie21woahhphb55nscz virtualenv]# pip install virtualenv
[root@izwz9ie21woahhphb55nscz virtualenv]# virtualenv venv   #创建环境名为venv的独立环境
Using base prefix '/usr/local'
New python executable in /root/virtualenv/venv/bin/python3.6
Also creating executable in /root/virtualenv/venv/bin/python
Please make sure you remove any previous custom paths from your /root/.pydistutils.cfg file.
Installing setuptools, pip, wheel...done.
#进入环境
[root@izwz9ie21woahhphb55nscz virtualenv]# source ./venv/bin/activate
(venv) [root@izwz9ie21woahhphb55nscz virtualenv]# 
然后想干嘛就干嘛,完全隔离的环境
#退出隔离环境
(venv) [root@izwz9ie21woahhphb55nscz virtualenv]# deactivate
[root@izwz9ie21woahhphb55nscz virtualenv]# 

ref:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432712108300322c61f256c74803b43bfd65c6f8d0d0000

Java远程执行shell命令

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import java.io.*;

public class RemoteExecuteCommand {
    private static String DEFAULTCHART = "UTF-8";
    private static Connection conn;
    private String ip;
    private String userName;
    private String userPwd;

    public RemoteExecuteCommand(String ip, String userName, String userPwd) {
        this.ip = ip;
        this.userName = userName;
        this.userPwd = userPwd;
    }

    public Boolean login() throws IOException {
        boolean flg = false;
        conn = new Connection(ip);
        conn.connect();//连接
        flg = conn.authenticateWithPassword(userName, userPwd);//认证
        if (flg) {
            System.out.println("认证成功!");
        } else {
            System.out.println("认证失败!");
        }

        return flg;
    }

    public String executeParse(String cmd) throws IOException {
        StringBuffer buffer = new StringBuffer();
        if (login()) {
            Session session = conn.openSession();//打开一个会话
            session.requestPTY("bash");
            session.startShell();
            PrintWriter out = new PrintWriter(session.getStdin());
            out.println(cmd);
            out.println("exit");
            out.close();
            session.waitForCondition(ChannelCondition.CLOSED | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS , 30000);
            InputStream stdout = new StreamGobbler(session.getStdout());
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line + "\n");
            }
            if (session != null) {
                session.close();
            }
            if (conn != null) {
                conn.close();
            }
        }
        return buffer.toString();
    }

//    public static void main(String[] args) throws IOException {
//        RemoteExecuteCommand rec1 = new RemoteExecuteCommand("***.***.***.***", "root", "*******");
//        RemoteExecuteCommand rec2 = new RemoteExecuteCommand("***.***.***.***", "root", "*******");
//        RemoteExecuteCommand rec3 = new RemoteExecuteCommand("***.***.***.***", "root", "*******");
//        String cmd1 = "/root/zookeeper-3.4.12/bin/zkServer.sh start";
//        String cmd2 = "nohup /root/kafka_2.11-1.1.0/bin/kafka-server-start.sh /root/kafka_2.11-1.1.0/config/server.properties >nohup_kafka 2>&1 &";
//        String cmd3 = "nohup /root/metricbeat-6.3.1-linux-x86_64/metricbeat -e -c  /root/metricbeat-6.3.1-linux-x86_64/metricbeat.yml >nohup_metricbeat 2>&1 &";
//        System.out.println(rec1.executeParse(cmd1));
//        System.out.println(rec2.executeParse(cmd2));
//        System.out.println(rec3.executeParse(cmd3));
//    }
}

Jar:https://mvnrepository.com/artifact/org.jvnet.hudson/ganymed-ssh-2/build260

Ref:https://www.cnblogs.com/-wangjiannan/p/3751330.html最佳

https://blog.csdn.net/hpp1314520/article/details/72918723容易出现命令不执行的情况(比如nohup)

Java操作MySQL(JDBC) 数据库

import java.sql.*;
import java.util.*;

public class BaseDao {
    private static String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true";
    private static String user = "root";
    private static String pwd = "123456";
    private static Connection conn;
    private static PreparedStatement pstmt;
    private static ResultSet rs;

    // 1.加载驱动(静态代码块)
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //2.建立连接
    private static void getConn() {
        if (conn == null) {
            try {
                conn = DriverManager.getConnection(url, user, pwd);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //读
    public static ResultSet query(String sql, List<Object> params) {
        getConn();
        try {
            pstmt = conn.prepareStatement(sql);
            if (params != null && params.size() > 0) {
                for (int i = 0; i < params.size(); i++) {
                    pstmt.setObject(i + 1, params.get(i));
                }
            }
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    //写
    public static int update(String sql, List<Object> params) {
        int result = 0;
        getConn();
        try {
            pstmt = conn.prepareStatement(sql);
            if (params != null && params.size() > 0) {
                for (int i = 0; i < params.size(); i++) {
                    pstmt.setObject(i + 1, params.get(i));
                }
            }
            result = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close();
        }
        return result;
    }

    //关闭连接
    public static void close() {
        try {
            if (rs != null) {
                rs.close();
                rs = null;
            }
            if (pstmt != null) {
                pstmt.close();
                pstmt = null;
            }
            if (conn != null) {
                conn.close();
                conn = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //获取数据库所有表
    public static List<String> getTables(){
        getConn();
        List<String> tables = new ArrayList<String>();
        try {
            DatabaseMetaData dbMetaData = conn.getMetaData();
            ResultSet rs = dbMetaData.getTables(null, null, null,new String[] { "TABLE" });
            while (rs.next()){
                tables.add(rs.getString("TABLE_NAME"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return tables;
    }

    //获取数据库某表的字段
    public static List<String> getColumns(String table){
        getConn();
        List<String> columns = new ArrayList<String>();
        String sql = "select * from " + table;
        getConn();
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            ResultSetMetaData meta = rs.getMetaData();
            int columeCount = meta.getColumnCount();
            for (int i = 1; i < columeCount + 1; i++) {
                columns.add(meta.getColumnName(i));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return columns;
    }

    //测试
    public static void main(String[] args) throws SQLException {

//        String sql="insert into metric(kkey,value)values(?,?)";
//        List<Object> params=new ArrayList<>();
////        params.add(1);
//        params.add("66666");
//        params.add("aaaaa5655aaaaaaaaaaaaaa");
//        System.out.println(update(sql,params));

        //查找
//        String sql="select id,kkey,value,name from metric where name=?";
//        List<Object> params=new ArrayList<>();
//        params.add("process");
//        ResultSet rs=query(sql,params);
//        while (rs.next()){
//            int id=rs.getInt("id");
//            String key=rs.getString("kkey");
//            String value=rs.getString("value");
//            String nm=rs.getString("name");
//
//            System.out.println("id:"+id+"name:"+nm+" key:"+key+" value:"+value);
//        }
        List<String> tables=getTables();
        List<String> columns=getColumns("admin");
        System.out.println("done");
    }
}

Error:可能无法update,原因是因为sql语句书写不正确,正确的写法见下面(致谢

    //写2
    public static int update2(String sql) {
        int result = 0;
        getConn();
        try {
            pstmt = conn.prepareStatement(sql);
            result = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close();
        }
        return result;
    } 
   public String updateStatus(@RequestParam("id") String id, @RequestParam("field") String field, @RequestParam("state") String state,@RequestParam("table") String table) {
        String sql = "update "+table+" set "+field+" = '"+state +"' where id='"+id+"'";
        System.out.println(sql);
        int rs=PatternDao.update2(sql);
        System.out.println("rs:"+rs);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", "");
        if(rs>0)
            jsonObject.put("code", 0);
        else
            jsonObject.put("code", -1);

        return JSONObject.toJSONString(jsonObject);
    }

jdbchttps://dev.mysql.com/downloads/connector/j/

refhttps://www.cnblogs.com/zhangdiIT/p/6772543.html#commentform

Mysql:统计一列中不同值的数量

表结构

mysql> desc metric;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| kkey  | varchar(50) | YES  |     | NULL    |                |
| value | text        | YES  |     | NULL    |                |
| name  | varchar(20) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

1.法一:最牛逼的

mysql> select name,count(*) num from  metric group by name;
+---------+-----+
| name    | num |
+---------+-----+
| load    |   1 |
| network |   4 |
| process | 268 |
+---------+-----+

2.法二:count() 需要提前知道该列中的具体值。

mysql> select count(name='load' or  null) as 'load',count(name='network' or null) as network,count(name='process' or null) as process from metric;
+------+---------+---------+
| load | network | process |
+------+---------+---------+
|    1 |       4 |     268 |
+------+---------+---------+


加上or null 是因为count(null)=0;

3.法三:sum() 也需要提前知道该列中的具体值

mysql> select sum(name='load') as 'load',sum(name='network') as network,sum(name='process') as process from metric;
+------+---------+---------+
| load | network | process |
+------+---------+---------+
|    1 |       4 |     268 |
+------+---------+---------+

ref:https://www.cnblogs.com/cxxjohnson/p/7966766.html

问题:第一个as后面的别名需要加引号