由于DotNetCore的程序和web采用json配置了。为了用shell修改配置文件。用vim的话看的是整个配置,网上也有用sed正则表达式替换的例子。总的来说用shell操作json读写配置比较麻烦。为了弥补shell一些不便捷性,基于之前基础实现shellnet工具,就是shell的dotnet补充。
支持以下
作为用dotnet对shell的补充工具
#查看帮助
shellnet --help
#查看版本
shellnet --vertion
#读取指定名称json的指定路径值
shellnet -rjson /test.json userinfo.name
#读取指定名称json的指定路径值
shellnet -gjson /test.json userinfo.name
#修改指定名称json的指定路径的值。不显示成功的内容串
shellnet -wjson /test.json userinfo.name zlz
#修改指定名称json的指定路径的值。不显示成功的内容串
shellnet -sjson /test.json userinfo.name zlz
#修改指定名称json的指定路径的值。显示成功的内容串
shellnet -wvjson /test.json userinfo.name zlz
#修改指定名称json的指定路径的值。显示成功的内容串
shellnet -svjson /test.json userinfo.name zlz
工具代码
入口
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
namespace shellnet
{
///<summary NoteObject="Class">
/// [功能描述: shell操作不足的dotnet补充工具命令,实现一些用shell实现费劲的功能]<br></br>
/// [创建者: zlz]<br></br>
/// [创建时间: 20210711]<br></br>
/// <说明>
///
/// </说明>
/// <修改记录>
/// <修改时间></修改时间>
/// <修改内容>
///
/// </修改内容>
/// </修改记录>
/// </summary>
class Program
{
static void Main(string[] args)
{
//没参数提示
if(args==null||args.Length==0)
{
Console.WriteLine("no para please try shellnet --help");
return;
}
//第一个参数为操作
string oper = "";
oper = args[0];
//命令帮助
if (oper=="--help")
{
string helpPath = AppContext.BaseDirectory + "help.txt";
if(File.Exists(helpPath))
{
Console.WriteLine(TxtUtil.ReadTxt(helpPath));
}
else
{
Console.WriteLine("shellnet -rjson /test.json userinfo.name");
Console.WriteLine("shellnet -wjson /test.json userinfo.name zlz");
}
}
//命令版本
else if (oper=="--vertion")
{
Console.WriteLine("shellnet 0.0.1 20210714 zlz");
}
//读json
else if (oper=="-rjson"|| oper == "-gjson")
{
if(args.Length>=3)
{
string path = args[1];
string jpath = args[2];
if(File.Exists(path))
{
string jsonStr = TxtUtil.ReadTxt(path);
string val = JsonUtil.GetJsonValByRegPath(jsonStr, jpath);
Console.WriteLine(val);
}
}
}
//写json
else if (oper == "-wjson" || oper == "-sjson"||oper == "-wvjson" || oper == "-svjson")
{
if (args.Length >= 4)
{
string path = args[1];
string jpath = args[2];
string newval = args[3];
if (File.Exists(path))
{
string jsonStr = TxtUtil.ReadTxt(path);
string newJson = JsonUtil.SetJsonValByRegPath(jsonStr, jpath, newval);
if(newJson!=null&&newJson !="")
{
TxtUtil.WriteTxt(path, newJson,true);
if(oper.Contains("v"))
{
Console.WriteLine("success change to:");
Console.WriteLine(newJson);
}
else
{
Console.WriteLine("success");
}
}
}
else
{
Console.WriteLine("the file "+ path+ " not exist!");
}
}
else
{
Console.WriteLine("para error format!");
}
}
//正常输出
else
{
Console.WriteLine("no support command!");
}
}
/// <summary>
/// 给对象属性赋值
/// </summary>
/// <param name="obj">对象</param>
/// <param name="property">属性</param>
/// <param name="value">结果值</param>
public static void SetPropertyValue(Object obj, string propertyName, Object value)
{
PropertyInfo property = obj.GetType().GetProperty(propertyName);
if (property == null)
{
(obj as dynamic)[propertyName]=value;
}
//先获取该私有成员的数据类型
Type type = property.PropertyType;
//将值设置到对象中
property.SetValue(obj, value, null);
}
/// <summary>
/// 获取对象属性值
/// </summary>
/// <param name="obj">对象</param>
/// <param name="property">属性</param>
/// <returns>属性值</returns>
public static Object GetPropertyValue(Object obj, string propertyName)
{
PropertyInfo property = obj.GetType().GetProperty(propertyName);
if (property == null)
{
return null;
}
//获取属性值
return property.GetValue(obj, null);
}
}
}
文本工具类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace shellnet
{
///<summary NoteObject="Class">
/// [功能描述: Json操作工具]<br></br>
/// [创建者: zlz]<br></br>
/// [创建时间: 20210711]<br></br>
/// <说明>
///
/// </说明>
/// <修改记录>
/// <修改时间></修改时间>
/// <修改内容>
///
/// </修改内容>
/// </修改记录>
/// </summary>
public static class TxtUtil
{
/// <summary>
/// 读取文件数据
/// </summary>
/// <param name="path">文件全路径</param>
/// <returns></returns>
public static string ReadTxt(string path)
{
//文件流
FileStream fs = null;
StreamReader sr = null;
try
{
//创建文件流
fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//创建字符串读取器
sr = new StreamReader(fs);
//读到尾
string str = sr.ReadToEnd();
return str;
}
finally
{
if (fs != null)
{
fs.Close();
}
if (sr != null)
{
sr.Close();
}
}
}
/// <summary>
/// 写入数据到指定文件
/// </summary>
/// <param name="path">文件全路径</param>
/// <param name="str">数据</param>
/// <param name="isReplace">是否提换,默认为替换,否则为添加</param>
/// <returns></returns>
public static bool WriteTxt(string path, string str, bool isReplace = true)
{
FileStream fs = null;
StreamWriter sw1 = null;
try
{
//如果是替换,先清除之前的内容
if (isReplace)
{
if (File.Exists(path))
{
File.Delete(path);
}
}
//创建文件流
fs = new FileStream(path, FileMode.Append,FileAccess.Write);
//创建字符串写入器
sw1 = new StreamWriter(fs);
//写入字符串
sw1.Write(str);
return true;
}
finally
{
if (sw1 != null)
{
sw1.Close();
}
if (fs != null)
{
fs.Close();
}
}
}
}
}
json工具类,引用了Newtonsoft.Json
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace shellnet
{
///<summary NoteObject="Class">
/// [功能描述: Json操作工具]<br></br>
/// [创建者: zlz]<br></br>
/// [创建时间: 20210711]<br></br>
/// <说明>
///
/// </说明>
/// <修改记录>
/// <修改时间></修改时间>
/// <修改内容>
///
/// </修改内容>
/// </修改记录>
/// </summary>
public static class JsonUtil
{
/// <summary>
/// 设置Json的值,通过正则路径
/// </summary>
/// <param name="jsonStr">json串</param>
/// <param name="RegName">正则表达式或者直接路径userinfo.name</param>
/// <param name="value">设置的值</param>
/// <returns>返回新的Json串</returns>
public static string SetJsonValByRegPath(string jsonStr, string RegName, string value)
{
try
{
JToken jobj = JObject.Parse(jsonStr) as JToken;
//深度复制,防止遍历时候改变
JToken result2 = jobj.DeepClone();
var reader = jobj.CreateReader();
while (reader.Read())
{
if (reader.Value != null)
{
if (reader.TokenType == JsonToken.String || reader.TokenType == JsonToken.Integer || reader.TokenType == JsonToken.Float)
{
Regex reg = new Regex(@"" + RegName + "$");
if (reg.IsMatch(reader.Path))
{
result2.SelectToken(reader.Path).Replace(value);
}
}
}
}
jobj = result2;
return jobj.ToString();
}
catch (Exception ex)
{
}
return jsonStr;
}
/// <summary>
/// 通过路径正则表达式得到Json值
/// </summary>
/// <param name="jsonStr">Json串</param>
/// <param name="RegName">正则表达式或者直接路径userinfo.name</param>
/// <returns>目标值</returns>
public static string GetJsonValByRegPath(string jsonStr, string RegName)
{
if(jsonStr==null|| jsonStr=="")
{
return "";
}
if (RegName == null || RegName == "")
{
return jsonStr;
}
JToken jobj = JObject.Parse(jsonStr) as JToken;
string result = "";
try
{
var node = jobj.SelectToken("$.." + RegName);
if (node != null)
{
//判断节点类型
if (node.Type == JTokenType.String || node.Type == JTokenType.Integer || node.Type == JTokenType.Float)
{
//返回string值
result = node.Value<object>().ToString();
}
}
return result;
}
catch (Exception ex)
{
return "";
}
}
}
}
install的bash
#!/bin/bash
#shell放在网站上供在线执行下载和初步部署数据库目录等
#20210711
#zlz
#----------------------------------------------------------
#清空老文件夹
if [ -d /usr/local/shellnet ];then
echo "已安装shellnet,删除/usr/local/shellnet文件夹"
rm -rf /usr/local/shellnet
else
echo "alias shellnet='dotnet /usr/local/shellnet/shellnet.dll'">>~/.bashrc
fi
if ! type dotnet >/dev/null 2>&1; then
sudo yum install dotnet-runtime-5.0
fi
apppath=$(cd "$(dirname "$0")";pwd)"/shellnet"
cp -r ${apppath} /usr/local/
source ~/.bashrc
echo "安装成功"
包结构,到Linux上转换成tar.gz压缩包
解压安装
[root@localhost zlz]# cd /test
[root@localhost test]# ls
shellnet.tar.gz
[root@localhost test]# tar -xvf shellnet.tar.gz
shellnet/
shellnet/install
shellnet/shellnet/
shellnet/shellnet/help.txt
shellnet/shellnet/Newtonsoft.Json.dll
shellnet/shellnet/appsettings.json
shellnet/shellnet/shellnet.deps.json
shellnet/shellnet/shellnet.dll
shellnet/shellnet/shellnet.exe
shellnet/shellnet/shellnet.pdb
shellnet/shellnet/shellnet.runtimeconfig.dev.json
shellnet/shellnet/shellnet.runtimeconfig.json
[root@localhost test]# ls
shellnet shellnet.tar.gz
[root@localhost test]# cd shellnet
[root@localhost shellnet]# ls
install shellnet
[root@localhost shellnet]# bash install
已安装shellnet,删除/usr/local/shellnet文件夹
安装成功
运行测试
[root@localhost shellnet]# shellnet
no para please try shellnet --help
[root@localhost shellnet]# shellnet --help
作为用dotnet对shell的补充工具
#查看帮助
shellnet --help
#查看版本
shellnet --vertion
#读取指定名称json的指定路径值
shellnet -rjson /test.json userinfo.name
#读取指定名称json的指定路径值
shellnet -gjson /test.json userinfo.name
#修改指定名称json的指定路径的值。不显示成功的内容串
shellnet -wjson /test.json userinfo.name zlz
#修改指定名称json的指定路径的值。不显示成功的内容串
shellnet -sjson /test.json userinfo.name zlz
#修改指定名称json的指定路径的值。显示成功的内容串
shellnet -wvjson /test.json userinfo.name zlz
#修改指定名称json的指定路径的值。显示成功的内容串
shellnet -svjson /test.json userinfo.name zlz
由zlz提供,后期陆续加入shell实现麻烦的功能进来
[root@localhost shellnet]# shellnet --vertion
shellnet 0.0.1 20210714 zlz
[root@localhost shellnet]# shellnet -rjson shellnet/appsettings.json WebServiceAddress
http://127.0.0.1:57772/imedicallis/LIS.WS.DHCLISService.cls?wsdl=1&CacheUserName=_SYSTEM&CachePassword=SYS
[root@localhost shellnet]# shellnet -rjson shellnet/appsettings.json ServiceIP
127.0.0.1
[root@localhost shellnet]# shellnet -rjson shellnet/appsettings.json Logging.LogLevel.Default
Information
[root@localhost shellnet]# shellnet -wjson shellnet/appsettings.json Logging.LogLevel.Default Error
success
[root@localhost shellnet]# shellnet -wvjson shellnet/appsettings.json IsUseBD 1
success change to:
{
"Data": "RedisConnection",
"ConnectionStrings": {
"RedisConnection": "127.0.0.1:6379"
},
"Logging": {
"LogLevel": {
"Default": "Error",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"LISInnerInfo": "7B9376425C0C3FD6C42156E67EABB4C4",
"LicenseInfo": "",
"timeout": "30",
"ServiceIP": "127.0.0.1",
"WebServiceAddress": "http://127.0.0.1:57772/imedicallis/LIS.WS.DHCLISService.cls?wsdl=1&CacheUserName=_SYSTEM&CachePassword=SYS",
"DBType": "cache",
"ConnectionString": "",
"ConnectionString_Detail": "",
"ProConnectionString_Detail": "",
"CA_Config_Open": "",
"CSPAddress": "",
"CA_Config_Company": "",
"CA_CheckMode": "",
"IsMobileCA": "",
"LockUser": "",
"WebIP": "",
"CheckUrlPermission": "0",
"IsWriteTableLog": "1",
"IsReturnDBErr": "1",
"OrmCheckColInTime": "0",
"WebserviceVerify": "0",
"CurSysVertion": "",
"PublicKey": "",
"AutoRollbackTime": "",
"MsgServiceIP": "",
"ExtranetMsgServiceIP": "",
"MsgServicePort": "",
"ExtranetIP": "",
"MenuModel": "2",
"DisposeConnectionTime": "-1",
"IsUseBD": "1",
"IocConfPath": "Conf",
"StaticFilesPath": "UI"
}
[root@localhost shellnet]# cat shellnet/appsettings.json
{
"Data": "RedisConnection",
"ConnectionStrings": {
"RedisConnection": "127.0.0.1:6379"
},
"Logging": {
"LogLevel": {
"Default": "Error",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"LISInnerInfo": "7B9376425C0C3FD6C42156E67EABB4C4",
"LicenseInfo": "",
"timeout": "30",
"ServiceIP": "127.0.0.1",
"WebServiceAddress": "http://127.0.0.1:57772/imedicallis/LIS.WS.DHCLISService.cls?wsdl=1&CacheUserName=_SYSTEM&CachePassword=SYS",
"DBType": "cache",
"ConnectionString": "",
"ConnectionString_Detail": "",
"ProConnectionString_Detail": "",
"CA_Config_Open": "",
"CSPAddress": "",
"CA_Config_Company": "",
"CA_CheckMode": "",
"IsMobileCA": "",
"LockUser": "",
"WebIP": "",
"CheckUrlPermission": "0",
"IsWriteTableLog": "1",
"IsReturnDBErr": "1",
"OrmCheckColInTime": "0",
"WebserviceVerify": "0",
"CurSysVertion": "",
"PublicKey": "",
"AutoRollbackTime": "",
"MsgServiceIP": "",
"ExtranetMsgServiceIP": "",
"MsgServicePort": "",
"ExtranetIP": "",
"MenuModel": "2",
"DisposeConnectionTime": "-1",
"IsUseBD": "1",
"IocConfPath": "Conf",
"StaticFilesPath": "UI"
}
[root@localhost shellnet]#