コード例 #1
0
ファイル: InstanceController.cs プロジェクト: PnzJust/MyCloud
        public ActionResult Enable(string id)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Instance instance = db.Instances.SingleOrDefault(i => i.InstanceId.Equals(id));
                    if (instance != null)
                    {
                        SshClient sshclient = new SshClient("192.168.56.104", "test1234", "test1234");
                        sshclient.Connect();
                        SshCommand sc = sshclient.CreateCommand(@"sudo docker start " + instance.InstanceId.ToString());
                        sc.Execute();
                        sc = sshclient.CreateCommand(@"sudo docker exec " + instance.InstanceId.ToString() + @" sh -c /usr/sbin/sshd");
                        sc.Execute();
                        sshclient.Disconnect();

                        if (TryUpdateModel(instance))
                        {
                            instance.InstanceIsOn = true;
                            db.SaveChanges();
                        }
                        return(RedirectToAction("Index"));
                    }
                    return(HttpNotFound("Couldn't find the instance with id " + id.ToString()));
                }
                return(RedirectToAction("Index"));
            }
            catch (Exception e)
            {
                return(View("Error"));
            }
        }
コード例 #2
0
        public static String RunCommandWithFeedback(String host, String user, String passwd, String singleCommand)
        {
            StringBuilder feedback = new StringBuilder();

            try
            {
                feedback.AppendLine("Inizia esecuzione script:");
                PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(host, 22, user, passwd);
                connectionInfo.Timeout = TimeSpan.FromMilliseconds(40000);
                SshClient client = new SshClient(connectionInfo);
                client.Connect();
                SshCommand command = client.RunCommand(singleCommand);
                command.CommandTimeout = new TimeSpan(2000000000);
                feedback.AppendLine(command.Execute());
                feedback.AppendLine("disconnessione in corso");
                feedback.AppendLine(command.Execute("logout"));
                client.Disconnect();
                client.Dispose();

                feedback.AppendLine("disconnesso");
            }
            catch (Exception e)
            {
                feedback.AppendLine(Util.GetFormattedExceptionInfo(ref e));
            }
            return(feedback.ToString());
        }
コード例 #3
0
 public void close()
 {
     if (sshclient == null)
     {
         return;
     }
     using (SshClient tmpclient = new SshClient(sshParam.hostIP, sshParam.userName, sshParam.userPWD))
     {
         tmpclient.Connect();
         string killcmd = string.Format("ps -ef | grep '{0}' | grep -v grep | awk '{{print $2}}'", myTask.myRule.rFileName);
         if (myTask.hName.Length > 0)
         {
             killcmd = string.Format("ssh {0} \" {1} \"", myTask.hName, killcmd);
         }
         killcmd = string.Format("kill  `{0}`", killcmd);
         if (myTask.hName.Length > 0)
         {
             killcmd = string.Format("ssh {0} \" {1} \"", myTask.hName, killcmd);
         }
         SshCommand tmpcmd = tmpclient.CreateCommand(killcmd);
         tmpcmd.Execute();
         tmpcmd.Execute();
     }
     try
     {
         //sshcmd.CancelAsync();
         sshcmd.EndExecute(ssharesult);
         sshclient.Disconnect();
     }
     catch (Exception exc)
     {
     }
 }
コード例 #4
0
ファイル: InstanceController.cs プロジェクト: PnzJust/MyCloud
        public ActionResult Delete(string id)
        {
            try
            {
                Instance instance = db.Instances.Find(id);
                if (instance != null)
                {
                    SshClient sshclient = new SshClient("192.168.56.104", "test1234", "test1234");
                    sshclient.Connect();
                    SshCommand sc = sshclient.CreateCommand(@"sudo docker stop " + instance.InstanceId.ToString());
                    sc.Execute();
                    sc = sshclient.CreateCommand(@"sudo docker rm  " + instance.InstanceId.ToString());
                    sc.Execute();
                    sshclient.Disconnect();

                    db.Instances.Remove(instance);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
                return(HttpNotFound("Couldn't find the instance with id " + id.ToString()));
            }
            catch (Exception e)
            {
                return(View("Error"));
            }
        }
コード例 #5
0
ファイル: Deploy.cs プロジェクト: nibircse/installers
        /// <summary>
        /// Sends the SSH command with username/password authentication and timeout.
        /// <param name="hostname">The hostname.</param>
        /// <param name="port">The port.</param>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <param name="command">The command.</param>
        /// <param name="timeout">The timeout in minutes</param>
        /// <returns>
        /// exit code | output| error
        /// </returns>
        public static string SendSshCommand(string hostname, int port, string username, string password, string command, int timeout)
        {
            using (var client = new SshClient(hostname, port, username, password))
            {
                try
                {
                    client.Connect();

                    SshCommand scmd = client.CreateCommand(command);
                    //SshCommand scmd = client.RunCommand(command);
                    scmd.CommandTimeout = new TimeSpan(0, timeout, 0);
                    scmd.Execute();
                    int    exitstatus = scmd.ExitStatus;
                    string sresult    = scmd.Result;

                    if (sresult == null || sresult == "" || sresult == " ")
                    {
                        sresult = "Empty";
                    }
                    string serror = scmd.Error;
                    if (serror == null || serror == "")
                    {
                        serror = "Empty";
                    }
                    client.Disconnect();
                    client.Dispose();
                    return(exitstatus.ToString() + "|" + sresult + "|" + serror);
                }
                catch (Exception ex)
                {
                    return("1" + "|" + "Connection Error" + "|" + ex.Message);
                }
            }
        }
コード例 #6
0
        public List <string> GetIpAddresses()
        {
            // Get interface names
            // Note, don't depend on 'eth#" interface names, see https://superuser.com/a/1086705
            SshCommand netInterfaceNamesCmd = client.CreateCommand("ip -o link show | awk -F': ' '{print $2}'");

            netInterfaceNamesCmd.Execute();
            string[] netInterfaceNames = netInterfaceNamesCmd.Result.Trim().Split('\n');

            List <string> ipAddressesFound = new List <string>();

            foreach (string interfaceName in netInterfaceNames)
            {
                SshCommand netData = client.CreateCommand("ip -f inet addr show " + interfaceName + " | grep -Po 'inet \\K[\\d.]+'");
                netData.Execute();
                string ip = netData.Result.Trim();

                if (ip == "localhost" || ip == "127.0.0.1")
                {
                    continue;
                }

                ipAddressesFound.Add(ip);
            }

            return(ipAddressesFound);
        }
コード例 #7
0
        public virtual T Run()
        {
            if (!Client.IsConnected())
            {
                Client.Logger.Info("Client not connected, Connect.");
                Client.Connect();
            }

            Sshcmd = Client.Client.CreateCommand(CmdString);


            using (Sshcmd)
            {
                Client.Logger.Info($"Running command : {CmdString}.");
                _resultStr = Sshcmd.Execute();


                if (!string.IsNullOrEmpty(Sshcmd.Error))
                {
                    Client.Logger.Info($"Running command ({CmdString}) Error : {Sshcmd.Error}.");
                }

                Client.Logger.Info($"Return Value from command : {_resultStr}.");
                _state = QueryState.CommandSent;
            }

            var result = PaseResult(_resultStr);

            _state = QueryState.ResultParsed;
            //TODO Doods : QueryResult
            var queryResult = ToQueryResult(result);

            return(result);
        }
コード例 #8
0
        public bool TrySendCommand(String command, out String stdout, out String stderr)
        {
            bool result = false;

            stdout = String.Empty;
            stderr = String.Empty;


            try
            {
                using (SshClient ssh = new SshClient(_connectionInfo))
                {
                    ssh.Connect();
                    using (SshCommand cmd = ssh.CreateCommand(command))
                    {
                        cmd.Execute();
                    }
                    ssh.Disconnect();
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(String.Format("EXCEPTION: {0}", e.Message));
                result = false;
            }
            return(result);
        }
コード例 #9
0
        // todo uliser mutex différent pour avoir plusieurs commandes en même temps
        private void RunCommand(EventHandler <CommandEventArgs> fonctionRetour, string commande, int id, bool keepSubsciber)
        {
            VerrouMutex.WaitOne();

            if (client != null && !_disposed) // si la connexion n'a pas été détruite entre temps
            {
                if (client.IsConnected)       // si on a pas été déconnecté entre temps
                {
                    SshCommand sc = client.CreateCommand(commande);
                    sc.Execute();
                    string resultat = sc.Result;

                    // lance l'event de fin de commande pour notifier les subscibers du resultat
                    LaunchEvent(new CommandEventArgs(resultat, id, keepSubsciber), CommandeEvent);

                    // si les subscibers ne veulent recevoir le résultat qu'une fois
                    if (!keepSubsciber)
                    {
                        CommandeEvent -= fonctionRetour;
                    }
                }
            }

            VerrouMutex.ReleaseMutex();
        }
コード例 #10
0
        protected void Unzip(SshClient client, string targetPath)
        {
            SshCommand command   = null;
            var        directory = Path.GetDirectoryName(targetPath);
            var        filenameWithoutExtension = Path.GetFileNameWithoutExtension(targetPath);
            var        fileName = Path.GetFileName(targetPath);
            var        ext      = Path.GetExtension(targetPath);

            if (string.Equals("zip", ext, StringComparison.OrdinalIgnoreCase))
            {
                InstallZip(client);
                command = client.CreateCommand($"unzip -o -d {filenameWithoutExtension} {targetPath}");
            }
            else
            {
                command = client.CreateCommand($"cd {directory}; mkdir -p {filenameWithoutExtension}; tar zxvf {fileName} -C {directory}/{filenameWithoutExtension}");
            }

            var result = command.Execute();

            if (command.Error != "")
            {
                throw new Exception(command.Error);
            }
        }
コード例 #11
0
 private void UnpairWithComputer(SshClient client)   // prekinemo seznanitev pc-ja in pi-a
 {
     if (client != null)
     {
         IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName())
                        .Where(address => address.AddressFamily == AddressFamily.InterNetwork).First();
         SshCommand listCommand = client.CreateCommand("moonlight unpair " + ip.ToString());
         string     result      = listCommand.Execute();
         if (result.Contains("error"))
         {
             MessageBox.Show("Napaka pri odstranjevanju povezave.");
         }
         else if (result.Contains("never"))
         {
             MessageBox.Show("Računalnik ni bil seznanjen s napravo.");
             isPaired     = false;
             button3.Text = "Seznani ta PC";
         }
         else
         {
             MessageBox.Show("Računalnik in naprava nista več seznanjena.");
             isPaired     = false;
             button3.Text = "Seznani ta PC";
         }
     }
     else
     {
         MessageBox.Show("Ni vzpostavljene povezave z napravo.");
     }
 }
コード例 #12
0
        private List <String> GetGameList(SshClient client)  // pridobimo seznam vseh možnih iger
        {
            SshCommand listCommand = client.CreateCommand("moonlight list");

            listCommand.Execute();
            string resultCommand = listCommand.Result;

            string[]      result   = resultCommand.Split('\n');
            List <String> allGames = new List <string>();

            if (result[1].Contains("Connect to"))
            {
                for (int i = 2; i < result.Length; i++)
                {
                    if (result[i].Contains(i - 1 + "."))
                    {
                        string game = result[i].Substring(result[i].IndexOf('.') + 2);
                        allGames.Add(game);
                    }
                }
            }
            if (allGames.Count == 0)
            {
                MessageBox.Show("Ni najdenih kompatibilnih iger :(");
                return(null);
            }
            return(allGames);
        }
コード例 #13
0
        /// <summary>
        /// Executes a synchronous command
        /// </summary>
        /// <param name="result">The result object for the current operation</param>
        /// <param name="command">The definition of the command to execute</param>
        /// <param name="sshCommand">The SSH command object to execute</param>
        private static void ExecuteSyncCommand(OperationResult result, SyncCommand command, SshCommand sshCommand)
        {
            sshCommand.Execute();
            Logger.WriteLine("Command returned exit code {0}", sshCommand.ExitStatus.ToString());
            Logger.WriteRaw(sshCommand.Result, LogLevel.Debug);

            if (!command.SuccessCodes.Contains(sshCommand.ExitStatus))
            {
                if (!string.IsNullOrWhiteSpace(sshCommand.Error))
                {
                    throw new Microsoft.MetadirectoryServices.ExtensibleExtensionException(sshCommand.Error);
                }
                else
                {
                    throw new Microsoft.MetadirectoryServices.ExtensibleExtensionException("The command returned an exit code that was not in the list of successful exit codes: " + sshCommand.ExitStatus.ToString());
                }
            }

            if (command.HasObjects)
            {
                result.ExecutedCommandsWithObjects.Add(sshCommand);
            }

            result.ExecutedCommands.Add(sshCommand);
        }
コード例 #14
0
        /// <summary>
        /// コマンドを実行する
        /// </summary>
        /// <param name="command"></param>
        public void Command(string command)
        {
            if (client == null)
            {
                Debug.LogError("NOT Connected Server");
                return;
            }

            try {
                // コマンドの作成
                SshCommand cmd = client.CreateCommand(command);

                // コマンドの実行
                cmd.Execute();

                if (cmd.Result != string.Empty)
                {
                    successEvent.Invoke(cmd.Result);
                }
                if (cmd.ExitStatus != 0 && cmd.Error != string.Empty)
                {
                    failureEvent.Invoke(cmd.Error);
                }
            } catch (Exception e) {
                Debug.Log(e.Message);
            }
        }
コード例 #15
0
        public void Register(String username)
        {
            if (ssh == null)
            {
                try
                {
                    ssh = new SshClient("137.112.128.188", "mpd", "mpd");
                    ssh.Connect();
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine("Problems connecting to music server, try registering later!");
                    DBAccessor.deleteEntry("Users", "Username = "******"cat port");
            String     portnum    = cmd1.Execute();
            int        portnumnum = int.Parse(portnum);
            int        streamPort = portnumnum + 1;
            SshCommand command    = ssh.CreateCommand("echo 'user \"mpd\"\nport \"" + portnumnum + "\"\nrestore_paused \"no\"\npid_file \"/run/mpd/" + username + ".pid\"\ndb_file \"/var/lib/mpd/mpd.db\"\nstate_file \"/var/lib/mpd/userstates/" + username + ".mpdstate\"\nplaylist_directory \"/var/lib/mpd/playlists\"\nmusic_directory \"/var/lib/mpd/music\"\naudio_output {\n\ttype\t\"httpd\"\n\tbind_to_address\t\"137.112.128.188\"\n\tname\t\"My HTTP Stream\"\n\tencoder\t\"lame\"\n\tport\t\"" + streamPort + "\" \n\tbitrate\t\"320\"\n\tformat\t\"44100:16:1\"\n}' > userconfs/" + username + ".conf");

            command.Execute();
            //StreamPort = portnumnum;
            portnumnum += 2;
            SshCommand cmd2 = ssh.CreateCommand("echo \"" + portnumnum + "\" > port");

            cmd2.Execute();
            //           ssh.Disconnect();
        }
コード例 #16
0
        private void OnFunctionButton_Click(object sender, EventArgs e)
        {
            if (!m_CurrentClient.IsConnected)
            {
                MessageBox.Show("Already disconnect!", "Already disconnect!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                UpdateDisplay();
                return;
            }

            int      index    = (int)((Button)sender).Tag;
            Function function = m_CurrentConfig.Functions[index];

            m_CommandResultCache.Clear();
            SshCommand command = m_CurrentClient.CreateCommand("");

            for (int iCommand = 0; iCommand < function.Commands.Length; iCommand++)
            {
                command.Execute(function.Commands[iCommand]);
                m_CommandResultCache.AppendLine("# " + command.CommandText);
                m_CommandResultCache.AppendLine(command.Result);
                if (!string.IsNullOrEmpty(command.Error))
                {
                    m_CommandResultCache.AppendLine("Error:");
                    m_CommandResultCache.AppendLine(command.Error);
                }
            }

            MessageBox.Show(m_CommandResultCache.ToString(), "Function Result!", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
コード例 #17
0
        public void SendCommand(string command)
        {
            SshCommand sc = this.client.CreateCommand(command);

            sc.Execute();
            Console.WriteLine(sc.Result);
        }
コード例 #18
0
        public override bool DetectedFault()
        {
            _fault                 = new Fault();
            _fault.type            = FaultType.Fault;
            _fault.detectionSource = "SshMonitor";
            _fault.folderName      = "SshMonitor";

            try
            {
                using (SshCommand cmd = _sshClient.RunCommand(Command))
                {
                    _fault.title       = "Response";
                    _fault.description = cmd.Execute();

                    bool match = _regex.IsMatch(_fault.description);

                    if (match)
                    {
                        _fault.type = FaultOnMatch ? FaultType.Fault : FaultType.Data;
                    }
                    else
                    {
                        _fault.type = FaultOnMatch ? FaultType.Data : FaultType.Fault;
                    }
                }
            }
            catch (Exception ex)
            {
                _fault.title       = "Exception";
                _fault.description = ex.Message;
            }

            return(_fault.type == FaultType.Fault);
        }
コード例 #19
0
        /// <summary>
        /// Connect to an SSH.
        /// </summary>
        /// <param name="targetIP">The <see cref="string"/> instance that represents the target IP.</param>
        /// <param name="user">The <see cref="string"/> instance that represents the login.</param>
        /// <param name="pass">The <see cref="string"/> instance that represents the password.</param>
        /// <returns>An instance of the <see cref="SshResponse"/> class representing the result of the connection, an <see cref="Exception"/> if error; otherwise, an uname.</returns>
        private SshResponse meet(string targetIP, string user, string pass)
        {
            SshResponse response = new SshResponse();

            try
            {
                using (var client = new SshClient(targetIP, user, pass))
                {
                    client.ConnectionInfo.Timeout = TimeSpan.FromMilliseconds(timeout);
                    client.Connect();

                    SshCommand runcommand = client.CreateCommand("uname -a");
                    runcommand.CommandTimeout = TimeSpan.FromMilliseconds(10000);
                    response.uname            = runcommand.Execute();;

                    client.Disconnect();
                }
            }
            catch (Exception wank)
            {
                // System.Net.Sockets.SocketException
                // Renci.SshNet.Common.SshOperationTimeoutException
                // System.AggregateException 
                response.Exception = wank;
                //response.Exeception = new Exception();
            }

            return(response);
        }
コード例 #20
0
ファイル: frmMain.cs プロジェクト: Crash0v3r1de/SSHBuddy
 private void windowsToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (connected)
     {
         using (PingTargetUI pUI = new PingTargetUI())
         {
             pUI.ShowDialog();
             if (!String.IsNullOrWhiteSpace(pUI.target))
             {
                 UpdateStatus("Sending Commands...");
                 SshCommand sc = sshClient.CreateCommand($"ping {pUI.target}");
                 sc.Execute();
                 string answer = sc.Result;
                 if (!String.IsNullOrWhiteSpace(answer))
                 {
                     UpdateStatus("Command Completed!");
                     txtConsole.Text = "";
                     txtConsole.Text = answer;
                 }
                 else
                 {
                     UpdateStatus("Command Failed!");
                 }
             }
             else
             {
                 UpdateStatus("Input Missing!");
             }
         }
     }
     else
     {
         MessageBox.Show("SSH client is NOT connected!");
     }
 }
コード例 #21
0
ファイル: Form1.cs プロジェクト: yunuscanyc/reklam
        private void button4_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = MessageBox.Show("Cihaz yeniden başlatılacak, emin misiniz?", "Dikkat", MessageBoxButtons.YesNo);

            if (dialogResult == DialogResult.No)
            {
                return;
            }

            Ping pinger = null;

            pinger = new Ping();
            PingReply reply = pinger.Send(listcihazlar.Items[listcihazlar.SelectedIndices[0]].SubItems[3].Text, 10);

            if (reply.Status == IPStatus.Success)
            {
                SshClient sshclient = new SshClient(listcihazlar.Items[listcihazlar.SelectedIndices[0]].SubItems[3].Text, "pi", "1");
                sshclient.Connect();
                SshCommand sc = sshclient.CreateCommand("sudo shutdown -r now");
                try
                {
                    sc.Execute();
                }
                catch
                {
                }
            }
            else
            {
                MessageBox.Show("Belirtilen cihaza uzaktan bağlantı yok.");
            }
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: waffielz/discord-bot
        private static async Task GameAdminList(SocketMessage message, ServerConnection serverConnection)
        {
            using (SshClient sshClient = new SshClient(serverConnection.Ip, serverConnection.Login, serverConnection.Password))
            {
                sshClient.Connect();
                await message.Channel.SendMessageAsync($"Connection successful");

                await message.Channel.SendMessageAsync($"Getting ban list");

                SshCommand cmd       = sshClient.CreateCommand("cat ./server/Unitystation-Server_Data/StreamingAssets/admin/banlist.json");
                string     cmdResult = cmd.Execute();
                sshClient.Disconnect();

                BanList banList = JsonSerializer.Deserialize <BanList>(cmdResult);

                StringBuilder stringBuilder = new StringBuilder();
                foreach (BanEntry banEntry in banList.banEntries)
                {
                    stringBuilder.Append($"{banEntry.userName}\n");
                }

                await message.Channel.SendMessageAsync($">>> **Banned users:**\n{stringBuilder.ToString()}");

                await message.Channel.SendMessageAsync($"Use **!gameban servername get username** to see details");
            }
        }
コード例 #23
0
ファイル: Program.cs プロジェクト: waffielz/discord-bot
        private async Task Ufw(SocketMessage message)
        {
            List <string> commandParams = message.Content.Split(" ").ToList();

            if (commandParams.Count != 3)
            {
                await message.Channel.SendMessageAsync($"Usage: !ufw deny ip");

                return;
            }

            if (commandParams[1] != "deny")
            {
                await message.Channel.SendMessageAsync($"Unknown verb. Usage: !ufw deny ip");

                return;
            }

            foreach (ServerConnection serverConnection in config.ServersConnections)
            {
                using (SshClient sshClient = new SshClient(serverConnection.Ip, serverConnection.Login, serverConnection.Password))
                {
                    sshClient.Connect();
                    await message.Channel.SendMessageAsync($"Connection to {serverConnection.ServerName} successful");

                    await message.Channel.SendMessageAsync($"Adding {commandParams[2]} to deny rule list");

                    SshCommand cmd = sshClient.CreateCommand($"ufw insert 1 deny from {commandParams[2]} to any");
                    cmd.Execute();
                    sshClient.Disconnect();
                }
            }
        }
コード例 #24
0
        public virtual T Run()
        {
            if (!Client.IsConnected())
            {
                Logger.Instance.Info($"Client not connected, Connect.");
                Client.Connect();
            }
            Sshcmd = Client.Client.CreateCommand(CmdString);


            string str;

            using (Sshcmd)
            {
                Logger.Instance.Info($"Running command : {CmdString}.");
                str = Sshcmd.Execute();
                Logger.Instance.Info($"Return Value from command : {str}.");
            }

            var result = PaseResult(str);
            //TODO Doods : QueryResult
            var objres = new QueryResult <T>()
            {
                Query      = CmdString,
                BashLines  = str,
                Result     = result,
                ExitStatus = Sshcmd.ExitStatus,
                Error      = Sshcmd.Error
            };

            return(result);
        }
コード例 #25
0
ファイル: Program.cs プロジェクト: waffielz/discord-bot
        private static async Task GameAdminGet(SocketMessage message, ServerConnection serverConnection, string userName)
        {
            using (SshClient sshClient = new SshClient(serverConnection.Ip, serverConnection.Login, serverConnection.Password))
            {
                sshClient.Connect();
                await message.Channel.SendMessageAsync($"Connection successful");

                await message.Channel.SendMessageAsync($"Getting ban details");

                SshCommand cmd       = sshClient.CreateCommand("cat ./server/Unitystation-Server_Data/StreamingAssets/admin/banlist.json");
                string     cmdResult = cmd.Execute();
                sshClient.Disconnect();

                BanList  banList    = JsonSerializer.Deserialize <BanList>(cmdResult);
                BanEntry bannedUser = banList.banEntries.FirstOrDefault(p => p.userName == userName);

                if (bannedUser == null)
                {
                    await message.Channel.SendMessageAsync($"That user is not in the ban list");

                    return;
                }

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append($"**User name:** {bannedUser.userName}\n");
                stringBuilder.Append($"**User id:** {bannedUser.userId}\n");
                stringBuilder.Append($"**Date of ban:** {bannedUser.dateTimeOfBan}\n");
                stringBuilder.Append($"**Minutes:** {bannedUser.minutes}\n");
                stringBuilder.Append($"**Reason:** {bannedUser.reason}");

                await message.Channel.SendMessageAsync($">>> **Banned user:**\n{stringBuilder.ToString()}");
            }
        }
コード例 #26
0
ファイル: SQLExecuter.cs プロジェクト: YanaPIIDXer/AnpanMMO
        /// <summary>
        /// コマンド実行.
        /// </summary>
        /// <param name="Client">SSHクライアント</param>
        /// <param name="Command">コマンド</param>
        /// <param name="Result">結果</param>
        /// <returns>成功したらtrueを返す</returns>
        private bool ExecuteCommand(SshClient Client, string Command, out string Result, out string Error)
        {
            Result = "";
            Error  = "";
            bool bCommandSuccess = false;

            try
            {
                using (SshCommand Cmd = Client.CreateCommand(Command))
                {
                    Cmd.Execute();
                    Result          = Cmd.Result;
                    bCommandSuccess = (Cmd.ExitStatus == 0);
                    if (!bCommandSuccess)
                    {
                        Error = Cmd.Error;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("");
                Console.WriteLine(e.Message);
                return(false);
            }

            return(bCommandSuccess);
        }
コード例 #27
0
ファイル: Program.cs プロジェクト: Dankerprouduct/sshclient
        static void Main(string[] args)
        {
            using (var client = new SshClient("10.146.3.39", "pi", "raspberry"))
            {
                client.Connect();

                if (client.IsConnected)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("connected");
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                while (true)
                {
                    string     input   = Console.ReadLine();
                    SshCommand command = client.CreateCommand(input);

                    command.Execute();

                    Console.WriteLine("sent command");

                    Thread.Sleep(500);

                    Console.WriteLine(command.Result);

                    Console.WriteLine(command.Error);

                    Console.WriteLine(command.ExtendedOutputStream);
                }
            }
        }
コード例 #28
0
ファイル: InvokeSshCommand.cs プロジェクト: tgiqfe/PSSsh
        protected override void ProcessRecord()
        {
            //  Commandファイルから読み取り
            if ((this.Command == null || this.Command.Length == 0) &&
                !string.IsNullOrEmpty(this.CommandFile) && File.Exists(this.CommandFile))
            {
                string text = File.ReadAllText(this.CommandFile);
                this.Command = pattern_return.Split(text);
            }

            this.Session ??= new SshSession()
            {
                Server              = this.Server,
                Port                = this.Port,
                User                = this.User,
                Password            = this.Password,
                KeyboardInteractive = this.KeyboardInteractive,
                Effemeral           = true, //  コマンドパラメータでSession指定が無い場合、Effemeral。
            };

            var client = Session.CreateAndConnectSshClient();

            if (client.IsConnected)
            {
                foreach (string line in Command)
                {
                    SshCommand command = client.CreateCommand(line);
                    command.Execute();

                    /*
                     * List<string> splitResult = pattern_return.Split(command.Result).ToList();
                     *
                     * if (splitResult.Count > 0 && string.IsNullOrEmpty(splitResult[0]))
                     * {
                     *  splitResult.RemoveAt(0);
                     * }
                     * if (splitResult.Count > 0 && string.IsNullOrEmpty(splitResult[splitResult.Count - 1]))
                     * {
                     *  splitResult.RemoveAt(splitResult.Count - 1);
                     * }
                     */
                    var splitResult = pattern_return.Split(command.Result).Trim();

                    if (string.IsNullOrEmpty(this.OutputFile))
                    {
                        WriteObject(string.Join("\r\n", splitResult), true);
                    }
                    else
                    {
                        TargetDirectory.CreateParent(this.OutputFile);
                        using (var sw = new StreamWriter(OutputFile, true, new UTF8Encoding(false)))
                        {
                            sw.Write(string.Join("\r\n", splitResult));
                        }
                    }
                }
            }
            Session.CloseIfEffemeral();
        }
コード例 #29
0
ファイル: SftpFilesystem.cs プロジェクト: zweecn/sshfs4win
 private IEnumerable <int> GetUserGroupsIds()
 {
     using (var cmd = new SshCommand(Session, "id -G "))
     {
         cmd.Execute();
         return(cmd.Result.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse));
     }
 }
コード例 #30
0
 public remote_directory(string host, SshCommand command)
 {
     this.host    = host;
     this.path    = command.Execute("pwd");
     this.path    = this.path.Replace('\n', '/');
     this.command = command;
     read_directory();
 }
コード例 #31
0
ファイル: SshCommandTest.cs プロジェクト: delfinof/ssh.net
 [Ignore] // placeholder for actual test
 public void ExecuteTest1()
 {
     Session session = null; // TODO: Initialize to an appropriate value
     string commandText = string.Empty; // TODO: Initialize to an appropriate value
     var encoding = Encoding.UTF8;
     SshCommand target = new SshCommand(session, commandText, encoding); // TODO: Initialize to an appropriate value
     string commandText1 = string.Empty; // TODO: Initialize to an appropriate value
     string expected = string.Empty; // TODO: Initialize to an appropriate value
     string actual;
     actual = target.Execute(commandText1);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }