栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

C# .Net SshClient 切换到ROOT用户 Su

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C# .Net SshClient 切换到ROOT用户 Su

借助linux shell 切换到ROOT用户

1-安装expect

    # wget https://sourceforge.net/projects/tcl/files/Tcl/8.4.19/tcl8.4.19-src.tar.gz
    # tar zxvf tcl8.4.19-src.tar.gz
    # cd tcl8.4.19/unix && ./configure
    # make
    # make install

    然后下载expect并安装。
   

    # wget http://sourceforge.net/projects/expect/files/Expect/5.45/expect5.45.tar.gz
    # tar zxvf expect5.45.tar.gz
    # cd expect5.45
    # ./configure --with-tcl=/usr/local/lib --with-tclinclude=/etc/apt/tcl8.4.19/generic
    # make
    # make install
    # ln -s /usr/local/bin/expect /usr/bin/expect

2-写脚本 su_root.sh

spawn su root
expect "Password:"
send "这里写root用户的密码r"

-------------------------------------------------上面那些不管用-------------------------------

ssh.RunCommand("echo "" + rootPwd + "" | sudo -S " + command);

试下这个命令!!!!!!!!!!!!!!!!!!!

c#中我封装成SuCommand了

using Renci.SshNet;
using System;
using System.IO;

namespace CommonUtils
{
    public static class SshUtil
    {
        static Map Passwords = new Map();
        static Map MachineNames = new Map();

        public static SshClient CreateClient(string host, string user, string pwd, double timeoutSeconds = 3.3)
        {
            var client = new SshClient(host, user, pwd);
            client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
            Passwords[client] = pwd;
            return client;
        }

        public static SshClient NewClient(string host, string user, string pwd, double timeoutSeconds = 3.3)
        => CreateClient(host, user, pwd, timeoutSeconds);

        public static SshClient NewConnect(string host, string user, string pwd, double timeoutSeconds = 3.3)
        => CreateClient(host, user, pwd, timeoutSeconds);

        public static void Open(this SshClient client)
        => client.Connect();

        public static void Close(this SshClient client)
        => client.Disconnect();

        public static string ResultAndError(this SshCommand command)
        => command.Result + command.Error;

        public static string Host(this SshClient client)
        => client.ConnectionInfo.Host;

        public static string Username(this SshClient client)
        => client.ConnectionInfo.Username;

        public static string OperateUser(this SshClient client)
        => client.RunCommand("who").Result.Split(" ")[0];

        public static string OperateMark(this SshClient client)
        => client.OperateUser() == "root" ? "#" : "$";

        public static string Password(this SshClient client)
        => Passwords[client];

        public static string MachineName(this SshClient client)
        {
            if (!MachineNames.ContainsKey(client))
                MachineNames[client] = client.RunCommand("uname -n").Result.Trim();
            return MachineNames[client];
        }

        public static string CurrentFolder(this SshClient client)
        => client.RunCommand("pwd").Result.Trim();

        public static string HeadInfo(this SshClient client)
        => StringUtil.Format("[{}@{} {}]{} ", client.OperateUser(), client.MachineName(), client.CurrentFolder(), client.OperateMark());

        public static string ExecuteCommand(this SshClient client, string command)
        {
            Console.WriteLine(client.HeadInfo() + command);
            var commander = client.CreateCommand(command);
            var result = commander.Execute() + commander.Error;
            if (result.Trim().IsNotEmpty())
                Console.WriteLine(result);
            return result;
        }

        public static string Command(this SshClient client, string command)
        => ExecuteCommand(client, command);

        public static string SuCommand(this SshClient client, string command)
        => ExecuteCommand(client, "echo "" + client.Password() + "" | sudo -S " + command);

        public static void Test(this SshClient client)
        => client.Command("ip addr");

        public static void Makedir(this SshClient client, string target)
        => client.Command("mkdir -p " + target);

        public static void MakeFileDir(this SshClient client, string target)
        => client.Command("mkdir -p " + target.Substring(0, target.LastIndexOf('/')));

        public static void UploadFolder(this SshClient client, string folder, string target)
        {
            var scp = new ScpClient(client.Host(), client.Username(), client.Password());
            Console.WriteLine(StringUtil.Format("rn[{}@scp]: try to upload {} to {}", client.Username(), folder, target));
            client.Makedir(target);
            scp.Connect();
            scp.Upload(new DirectoryInfo(folder), target);
            scp.Disconnect();
            Console.WriteLine(StringUtil.Format("[{}@scp]: upload success!rn", client.Username()));
        }

        public static void UploadFile(this SshClient client, string file, string target)
        {
            var scp = new ScpClient(client.Host(), client.Username(), client.Password());
            Console.WriteLine(StringUtil.Format("rn[{}@scp]: try to upload {} to {}", client.Username(), file, target));
            client.MakeFileDir(target);
            scp.Connect();
            scp.Upload(new FileInfo(file), target);
            scp.Disconnect();
            Console.WriteLine(StringUtil.Format("[{}@scp]: upload success!rn", client.Username()));
        }

        public static string GetIpConfig(this SshClient client)
        => client.ExecuteCommand("ifconfig");

        public static void PrintIpConfig(this SshClient client)
        => client.GetIpConfig().Print();

        public static SshConnectState TryConnect(this SshClient client, string displayPassword = "[hidden]")
        {
            LogUtil.PrintInfo("SshClient is trying to connect to {0} with user {1} and pwd {2}.",
                          client.ConnectionInfo.Host,
                          client.ConnectionInfo.Username,
                          displayPassword);
            try
            {
                var ipconfig = client.GetIpConfig();
                if (ipconfig.Length > 100)
                {
                    LogUtil.PrintInfo("SshClient connectted success!");
                    return SshConnectState.Success;
                }
                else
                {
                    LogUtil.PrintInfo("SshClient connectted fail!");
                    return SshConnectState.Fail;
                }
            }
            catch (Exception ex)
            {
                LogUtil.PrintInfo(ex.Message);

                var exName = ex.GetType().Name;
                switch (exName)
                {
                    case "SshOperationTimeoutException":
                        return SshConnectState.Timeout;

                    case "SshAuthenticationException":
                        return SshConnectState.AuthenticationDeny;

                    case "SocketException":
                        return SshConnectState.ProtocalDeny;

                    case "SshConnectionException":
                        return SshConnectState.ConnectionException;

                    default:
                        ex.HelpLink = client.ConnectionInfo.Host;
                        LogUtil.Record(ex);
                        return SshConnectState.Unknown;
                }
            }
        }

        public static SshConnectState TryConnect(string host, string user, string pwd, double timeoutSeconds)
        {
            var client = CreateClient(host, user, pwd, timeoutSeconds);
            return client.TryConnect(pwd);
        }

        public static bool CanConnect(this SshClient client, string displayPassword = "[hidden]")
        => client.TryConnect(displayPassword) == SshConnectState.Success;

        public static bool CanConnect(string host, string user, string pwd, double timeoutSeconds)
        => TryConnect(host, user, pwd, timeoutSeconds) == SshConnectState.Success;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/973356.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号