Example #1
0
		public static void RunExample()
		{
			try
			{
				SshConnectionInfo input = Util.GetInput();
				SshShell shell = new SshShell(input.Host, input.User);
				if(input.Pass != null) shell.Password = input.Pass;
				if(input.IdentityFile != null) shell.AddIdentityFile( input.IdentityFile );

				//This statement must be prior to connecting
				shell.RedirectToConsole();

				Console.Write("Connecting...");
				shell.Connect();
				Console.WriteLine("OK");

				while(shell.ShellOpened)
				{
					System.Threading.Thread.Sleep(500);
				}
				Console.Write("Disconnecting...");
				shell.Close();
				Console.WriteLine("OK");
			}
			catch(Exception e)
			{
				Console.WriteLine(e.Message);
			}
		}
Example #2
0
        private static string SshShell(string host, string command)
        {
            var shell = new SSH.SshShell(host.Split(':')[0], User, Password);

            if (host.Contains(":"))
            {
                shell.Connect(Int32.Parse(host.Split(':')[1]));
            }
            else
            {
                shell.Connect();
            }

            shell.Expect();

            string result = "";

            foreach (string cmd in command.Split('\n'))
            {
                shell.WriteLine(command);
                Thread.Sleep(1000);
                result += shell.Expect();
            }


            shell.Close();

            return(result);
        }
Example #3
0
    public override string ExecuteCommand(string command, string data)
    {
        try
        {
            // 获取服务器信息
            XDocument xser = XDocument.Parse(command);
            string lab_ip = xser.Element("IPLab").Element("LabIP").Value;
            si = Util.GetServerInfoFromIP(lab_ip);

            XDocument xdoc = XDocument.Parse(data);

            XElement filelist = xdoc.Element("IP_Lab").Element("StartList");
            XElement floder = xdoc.Element("IP_Lab").Element("Floder");
            ParseXMLtoList(filelist);

            SshShell shell = new SshShell(si.serverip, si.usrname, si.pwd);
            shell.Connect();
            if (shell.Expect(new Regex(si.sysname), 5) == null)
                throw new Exception("连接服务器出错!");

            if (CiscoSwitchList.Count > 0)
            {
                // 登录到设备上
                Util.SshWriteAndExpect(shell, "cd ~", si.sysname);
                Util.SshWriteAndExpect(shell, "ssh " + si.innerusrname + "@" + si.innerservip, "Password:"******" 启动失败!";
                }

                Util.SshWriteAndExpect(shell, "cd ~", si.innersysname);
                Util.SshWriteAndExpect(shell, "exit", si.sysname);
            }

            Util.SshWriteAndExpect(shell, "cd ~", si.sysname);

            foreach (FileBase file in FileList)
            {
                StartDevice sd = new StartDevice(file, shell, si.sysname);
                if (sd.Start())
                    continue;
                else
                    return sd.GetFileName() + " 启动失败!";
            }

            return "启动设备成功!";
        }
        catch (System.Exception ex)
        {
            return ex.Message;
        }
    }
Example #4
0
		public sshServer (string name,string host, string username, string password, string prompt)
		{
				this.name = name;
                this.username = username;
			try {
				thisServer = new SshShell (host, username, password);
				
				thisServer.Connect();
				thisServer.Expect(new Regex(username + "@" + ".*?#"));


					thisServer.RemoveTerminalEmulationCharacters = true;
			} catch (Exception e) {
				Console.WriteLine ("[ERROR] " + e.Message);	
			}
		}
Example #5
0
        public Client(string host,string username, string password)
        {
            this.Host = host;
            this.UserName = username;
            this.Password = password;

            //sshClient.ConnectionInfo.Username = "******";
            sshClient.Connect();

            ShowResponse = true;

            evt.Reset();

            shell = new SshShell(this.Host, this.UserName, this.Password);

            thr = new Thread(Read);
        }
Example #6
0
 private void btn_check_Click(object sender, EventArgs e)
 {
     SshShell ssh = new SshShell(tb_server.Text, tb_user.Text, tb_pass.Text);
     lbl_output.ForeColor = Color.Black;
     lbl_output.Text = "Connecting...";
     ssh.Connect((int)nud_port.Value);
     if (!ssh.Connected)
     {
         lbl_output.ForeColor = Color.Red;
         lbl_output.Text = "Could not Connect";
     }
     else
     {
         lbl_output.ForeColor = Color.Green;
         lbl_output.Text = "Connection OK";
     }
     ssh.Close();
 }
Example #7
0
		public static void RunExample()
		{
			try
			{
				SshConnectionInfo input = Util.GetInput();
				SshShell ssh = new SshShell(input.Host, input.User);
				if(input.Pass != null) ssh.Password = input.Pass;
				if(input.IdentityFile != null) ssh.AddIdentityFile( input.IdentityFile );

				Console.Write("Connecting...");
				ssh.Connect();
				Console.WriteLine("OK");

				
				Console.Write("Enter a pattern to expect in response [e.g. '#', '$', C:\\\\.*>, etc...]: ");
				string pattern = Console.ReadLine();
				
				ssh.ExpectPattern = pattern;
				ssh.RemoveTerminalEmulationCharacters = true;
				
				Console.WriteLine();
				Console.WriteLine( ssh.Expect( pattern ) );

				while(ssh.ShellOpened)
				{	
					Console.WriteLine();
					Console.Write("Enter some data to write ['Enter' to cancel]: ");
					string data = Console.ReadLine();
					if(data=="")break;
					ssh.WriteLine(data);

					string output = ssh.Expect( pattern );
					Console.WriteLine( output );
				}

				Console.Write("Disconnecting...");
				ssh.Close();
				Console.WriteLine("OK");
			}
			catch(Exception e)
			{
				Console.WriteLine(e.Message);
			}
		}
Example #8
0
        public void CheckJobStatus()
        {
            string stdout = "";
            //string stderr = "";
            bool atleastOne = false;
            SshShell shell = new SshShell(Consts.DEFAULT_HOST, Consts.DEFAULT_USERNAME, Consts.DEFAULT_PASSWORD);
            SshExec exec = new SshExec(Consts.DEFAULT_HOST, Consts.DEFAULT_USERNAME, Consts.DEFAULT_PASSWORD);
            Thread.Sleep(1000);

            string jobId;
            int runningJobs = 0;
            while (!atleastOne || runningJobs != 0)
            {
                stdout = runStatusCommand(shell, exec, "mapred job -list");
                runningJobs = Int32.Parse(stdout.Split(null).ToList()[0]);

                if (runningJobs != 0)
                {
                    atleastOne = true;
                    jobId = stdout.Split(null).ToList().Where(line => line.Contains("job_")).First();

                    double map;
                    double reduce;
                    while (true)
                    {
                        stdout = runStatusCommand(shell, exec, $"mapred job -status {jobId}");
                        map = Double.Parse((stdout.Split('\n').Where(line =>
                            line.Contains("map()")).First().ToString()).Split(null)[2]) * 100;
                        reduce = Double.Parse((stdout.Split('\n').Where(line =>
                            line.Contains("reduce()")).First().ToString()).Split(null)[2]) * 100;

                        StatusModel.Instance.setProgress((int)((reduce + map) / 2), 100);
                        StatusModel.Instance.Status = $"Map {(int)map}% - Reduce {(int)reduce}%";
                        if (reduce == 100) break;
                        Thread.Sleep(500);
                    }
                }
            }

            StatusModel.Instance.Status = "Finished MapReduce!";
        }
Example #9
0
        private static string SshShell(string host, string command)
        {
            var shell = new SSH.SshShell(host.Split(':')[0], User, Password);
            if (host.Contains(":"))
            {
                shell.Connect(Int32.Parse(host.Split(':')[1]));
            }
            else
            {
                shell.Connect();
            }

            shell.Expect();

            string result = "";

            foreach (string cmd in command.Split('\n'))
            {
                shell.WriteLine(command);
                Thread.Sleep(1000);
                result += shell.Expect();
            }

            shell.Close();

            return result;
        }
Example #10
0
 public SSHManager(string host, string username, string password)
 {
     _shell = new SshShell(host, username, password);
     _exec = new SshExec(host, username, password);
     _sshCp = new Scp(host, username, password);
 }
Example #11
0
        private string runStatusCommand(SshShell shell, SshExec exec, string command)
        {
            string stdout = "";
            string stderr = "";
            shell.Connect();
            shell.RedirectToConsole();
            exec.Connect();

            int ret = exec.RunCommand(command, ref stdout, ref stderr);

            exec.Close();
            shell.Close();
            return stdout;
        }
Example #12
0
    public override string ExecuteCommand(string command, string data)
    {
        try
        {
            // 获取服务器信息
            XDocument xser = XDocument.Parse(command);
            string lab_ip = xser.Element("IPLab").Element("LabIP").Value;
            si = Util.GetServerInfoFromIP(lab_ip);

            // 数据信息
            XDocument xdoc = XDocument.Parse(data);

            XElement filelist = xdoc.Element("IP_Lab").Element("FileList");
            XElement floder = xdoc.Element("IP_Lab").Element("Floder");
            FileList = ParseXMLtoList(filelist);

            SshShell shell = new SshShell(si.serverip, si.usrname, si.pwd);
            shell.Connect();
            if (shell.Expect(new Regex(si.sysname), 5) == null)
                throw new Exception("连接服务器出错!");

            // 首先,删除这个文件夹
            string flodername = floder.Value;

            Util.SshWriteAndExpect(shell, "cd ~", si.sysname);
            Util.SshWriteAndExpect(shell, "cd lab_script/", si.sysname);
            Util.SshWriteAndExpect(shell, "rm -rf " + flodername, si.sysname);

            CiscoSwitchList = new List<FileBase>();
            foreach (FileBase file in FileList)
            {
                if (file.deviceType == (int)DeviceType.DEVICE_TYPE_CISCOSWITCHER)
                {
                    // 对思科交换机的设备另行处理
                    CiscoSwitchList.Add(file);
                    continue;
                }
                FileToServer fts = new FileToServer(file, shell, si.sysname);
                if (fts.WriteFileToServer())
                    continue;
                else
                    return file.fileName + " 生成失败 !";
            }

            // 生成公共文件
            if (!GenerateCommonFile(xdoc.Element("IP_Lab"), shell))
                return "公共文件生成失败";

            // 存在思科交换机设备时,需要登录到其服务器
            if (CiscoSwitchList.Count > 0)
            {
                // 登录到设备上
                Util.SshWriteAndExpect(shell, "cd ~", si.sysname);
                Util.SshWriteAndExpect(shell, "ssh " + si.innerusrname + "@" + si.innerservip, "Password:"******"rm -rf ./iou/" + flodername, si.innersysname);
                // 生成配置文件
                foreach (FileBase file in CiscoSwitchList)
                {
                    FileToServer fts = new FileToServer(file, shell, si.innersysname);
                    if (fts.WriteFileToServer())
                        continue;
                    else
                        return file.fileName + " 生成失败 !";
                }

                string res = Util.SshWriteAndExpect(shell, "cd ~/iou/" + flodername, si.innersysname);
                if (!res.Contains("cd: can't cd to"))
                {
                    Util.SshWriteAndExpect(shell, "echo >> NETMAP", si.innersysname);
                    Util.SshWriteAndExpect(shell,
                        "cp /root/iou/lab_enterprise/IFMAP /root/iou/public/iou2net.pl /root/iou/public/iourc /root/iou/public/stop.sh ./ ",
                        si.innersysname);
                }
                else
                    return "思科交换机公共文件生成失败";
            }

            return "配置文件生成成功!";
        }
        catch (System.Exception ex)
        {
            return ex.Message;
        }
    }
        /// <summary>
        /// Main entry point
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            try
            {
                FilterInput(args);

                if (Args.Length == 0)
                {
                    Console.WriteLine("UsageDrupalUtil.exe COMMAND ARGUMENTS");
                    Console.WriteLine("By James Mc Parlane, [email protected]");
                    Console.WriteLine("(c) ThumbWhere, 2011");
                    Console.WriteLine("");
                    KnownCommands();
                    KnownOptions();
                    throw new ArgumentException("Called without arguments", "arguments");
                }

                Console.WriteLine("");
                Console.WriteLine("Arguments: ");
                foreach (string a in Args)
                {
                    Console.WriteLine("  {0}", a);
                }

                Console.WriteLine("");
                Console.WriteLine("Options: ");
                foreach (string o in Options)
                {
                    Console.WriteLine("  {0}", o);

                    switch (o)
                    {
                        // Set the recommended version
                        case "--recommended":
                            {
                                Recommended = true;
                            }
                            break;

                        // Set the supported version
                        case "--supported":
                            {
                                Supported = true;
                            }
                            break;

                        // Set the default version
                        case "--default":
                            {
                                Default = true;
                            }
                            break;

                        // Force something through, damn the horses.
                        case "--force":
                            {
                                Force = true;
                            }
                            break;

                        // Force something through, damn the horses.
                        case "--exitcleanonerror":
                            {
                                ExitCleanOnError = true;
                            }
                            break;

                        default:
                            {
                                throw new ArgumentException("Invalid option '" + o + "'", "options");
                            }
                    }
                }
                Console.WriteLine("");

                string command = Args[0];

                switch (command.ToLower())
                {
                    case "help":
                        {

                            if (Args.Length < 1)
                            {
                                NotEnoughArguments(command);
                                Environment.Exit(2);
                                return;
                            }

                            if (Args.Length == 2)
                            {
                                // Help on a specific comand
                                Usage(Args[1]);
                            }
                            else
                            {
                                // General help
                                KnownCommands();
                            }
                        }
                        break;

                    case "new":
                        {

                            if (Args.Length < 6)
                            {
                                NotEnoughArguments(command);
                                Environment.Exit(2);
                                return;
                            }

                            Console.WriteLine("");
                            Console.WriteLine("Creating new Module...");

                            //
                            // Parse the arguments
                            //

                            string name = Args[1].Trim();
                            string title = Args[2].Trim();
                            string maintainer = Args[3].Trim();
                            string api = Args[4].Trim();
                            string url = Args[5].Trim();

                            if (url.EndsWith("/")) url = url.Substring(0, url.Length - 1);

                            Console.WriteLine("");
                            Console.WriteLine("name       = '{0}'", name);
                            Console.WriteLine("title      = '{0}'", title);
                            Console.WriteLine("maintainer = '{0}'", maintainer);
                            Console.WriteLine("api        = '{0}'", api);
                            Console.WriteLine("url        = '{0}'", url);

                            Console.WriteLine("");

                            //
                            // Populate the XML Tempolate
                            //

                            XmlDocument xmlTemplate = new XmlDocument();
                            xmlTemplate.LoadXml(Resources.manifest_template);

                            XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(xmlTemplate.NameTable);

                            //Add the namespaces used in books.xml to the XmlNamespaceManager.
                            xmlnsManager.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");

                            xmlTemplate.SelectSingleNode("project/title").InnerText = title;
                            xmlTemplate.SelectSingleNode("project/short_name").InnerText = name;
                            xmlTemplate.SelectSingleNode("project/dc:creator", xmlnsManager).InnerText = maintainer;
                            xmlTemplate.SelectSingleNode("project/link").InnerText = url + "/" + name + "/";
                            xmlTemplate.SelectSingleNode("project/api_version").InnerText = api;

                            // Clear our any release information
                            xmlTemplate.SelectSingleNode("project/releases").RemoveAll();

                            //
                            // Create the new module
                            //

                            Directory.CreateDirectory(name);
                            Directory.CreateDirectory(name + "/" + api);

                            string xmlPath = name + "/" + api + "/manifest.xml";

                            if (File.Exists(xmlPath))
                            {
                                Console.WriteLine("There is already a manifest.xml file at '{0}'", xmlPath);
                                if (!Force)
                                {
                                    throw new ArgumentException("Safety feature - we don't let you overwrite if you don't specify --force");
                                }
                                else
                                {
                                    Console.WriteLine("... but you specified --force, and we all know what that means.");
                                }
                            }

                            Console.WriteLine("");
                            Console.WriteLine("Saving new XML to '{0}'", xmlPath);

                            // Save the XML
                            xmlTemplate.Save(xmlPath);

                            //
                            // Now save the XSL
                            //

                            XmlDocument xslTemplate = new XmlDocument();
                            xslTemplate.LoadXml(Resources.manifest);

                            string xslPath = name + "/" + api + "/manifest.xsl";

                            if (File.Exists(xslPath))
                            {
                                Console.WriteLine("There is already a manifest.xsl file at '{0}'", xslPath);
                                if (!Force)
                                {
                                    throw new ArgumentException("Safety feature - we don't let you overwrite if you don't specify --force");
                                }
                                else
                                {
                                    Console.WriteLine("... but you specified --force, and we all know what that means.");
                                }
                            }

                            Console.WriteLine("");
                            Console.WriteLine("Saving new XSL to '{0}'", xslPath);

                            // Save the XML
                            xslTemplate.Save(xslPath);

                        }
                        break;

                    case "add":
                        {

                            // Our version
                            int majorVersion = 0;
                            int patchVersion = 0;

                            // The base url
                            string url;

                            if (Args.Length < 5)
                            {
                                NotEnoughArguments(command);
                                Environment.Exit(2);
                                return;
                            }

                            Console.WriteLine("");
                            Console.WriteLine("Adding new release...");

                            //
                            // Parse the arguments
                            //

                            string folder = Args[1].Trim();
                            string name = Args[2].Trim();
                            string api = Args[3].Trim();
                            string increment = Args[4].Trim();

                            string type = "Bug fixes";
                            string stream = "release";
                            string build = "";

                            if (Args.Length > 5)
                            {
                                type = Args[5].Trim();
                            }

                            if (Args.Length > 6)
                            {
                                stream = Args[6].Trim();
                            }

                            if (Args.Length > 7)
                            {
                                build = Args[7].Trim();
                            }

                            Console.WriteLine("");
                            Console.WriteLine("folder    = '{0}'", folder);
                            Console.WriteLine("name      = '{0}'", name);
                            Console.WriteLine("api       = '{0}'", api);
                            Console.WriteLine("increment = '{0}'", increment);
                            Console.WriteLine("type      = '{0}'", type);
                            Console.WriteLine("stream    = '{0}'", stream);
                            Console.WriteLine("");

                            string xmlPath = name + "/" + api + "/manifest.xml";
                            Console.WriteLine("Loading XML from    {0}", xmlPath);

                            // Get the current manifest
                            XmlDocument xml = new XmlDocument();
                            xml.Load(xmlPath);

                            // Load the current template
                            XmlDocument xmlTemplate = new XmlDocument();
                            xmlTemplate.LoadXml(Resources.manifest_template);
                            XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(xmlTemplate.NameTable);

                            // Find our target releases element
                            XmlElement project = (XmlElement)xml.SelectSingleNode("project");

                            // Find our target releases element
                            XmlElement releases = (XmlElement)project.SelectSingleNode("releases");

                            // Create our new release element
                            XmlElement releaseElement = xml.CreateElement("release");

                            // Populate it
                            releaseElement.InnerXml = xmlTemplate.SelectSingleNode("project/releases/release").InnerXml;

                            // Get the base url
                            url = xml.SelectSingleNode("project/link").InnerText;
                            if (url.EndsWith("/")) url = url.Substring(0, url.Length - 1);

                            // If we have no children, then just add it
                            if (releases.ChildNodes.Count == 0)
                            {
                                // Create the new element
                                releases.AppendChild(releaseElement);
                            }
                            else
                            {
                                Console.WriteLine("There are {0} existing releases.", releases.ChildNodes.Count);

                                // If we have a current release.
                                XmlElement latestRelease = (XmlElement)releases.SelectSingleNode("release[starts-with(version,'" + api + "')]");

                                if (latestRelease != null)
                                {
                                    XmlElement majorVersionNode = (XmlElement)latestRelease["version_major"];
                                    XmlElement patchVersionNode = (XmlElement)latestRelease["version_patch"];

                                    majorVersion = int.Parse(majorVersionNode.InnerText);
                                    patchVersion = int.Parse(patchVersionNode.InnerText);

                                    Console.WriteLine("The latest release (for api '{0}') is {1}.{2}", api, majorVersion, patchVersion);

                                    switch (increment)
                                    {
                                        case "major":
                                            {

                                                Console.WriteLine("Incrementing major version, setting patch back to 0.");

                                                majorVersion++;
                                                patchVersion = 0;

                                            }
                                            break;

                                        case "patch":
                                            {
                                                Console.WriteLine("Incrementing minor version.");

                                                patchVersion++;
                                            }
                                            break;

                                        case "none":
                                            {
                                                Console.WriteLine("Incrementing no version.");
                                            }
                                            break;

                                        default:
                                            {
                                                throw new ArgumentException(increment + " is not a valid increment. Valid increments are major,patch,none.", "increment");
                                            }

                                    }

                                    Console.WriteLine("Created new release (for api '{0}') as version {1}.{2}", api, majorVersion, patchVersion);
                                }

                                // Create the new element
                                releases.InsertBefore(releaseElement, releases.FirstChild);
                            }

                            // Calculate the version
                            string version = api + "-" + majorVersion + "." + patchVersion + "-" + stream;

                            if (build != "")
                            {
                                version += "-build" + build;
                            }

                            Console.WriteLine("This version is known as '{0}'",version);

                            releaseElement.SelectSingleNode("name").InnerText = name + " " + version;
                            releaseElement.SelectSingleNode("version").InnerText = version;
                            releaseElement.SelectSingleNode("tag").InnerText = version;
                            releaseElement.SelectSingleNode("version_patch").InnerText = patchVersion.ToString();
                            releaseElement.SelectSingleNode("version_major").InnerText = majorVersion.ToString();
                            releaseElement.SelectSingleNode("release_link").InnerText = url + "/" + api + "/" + name + "-" + version + ".html";

                            string dateStamp = ((long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString();

                            releaseElement.SelectSingleNode("date").InnerText = dateStamp;

                            //
                            // Process the .info file
                            //

                            string infoFilePath = folder + "\\" + name + ".info";
                            string infoFileBackup = LoadFile(infoFilePath);
                            string infoFile = infoFileBackup;

                            try
                            {

                                //
                                // If we already have this -- comment it out
                                //

                                infoFile = infoFile.Replace("project status url =\"", ";project status url =\"");
                                infoFile = infoFile.Replace("version = \"", ";version =\"");
                                infoFile = infoFile.Replace("project = \"", ";project = \"");
                                infoFile = infoFile.Replace("datestamp = \"", ";datestamp = \"");

                                //
                                // Append the important odule information
                                //
                                infoFile += Environment.NewLine;
                                infoFile += Environment.NewLine;
                                infoFile += "; This information is purely for module updates" + Environment.NewLine;
                                infoFile += "project status url = \"" + url + "\"" + Environment.NewLine;
                                infoFile += "version = \"" + version + "\"" + Environment.NewLine;
                                infoFile += "project = \"" + name + "\"" + Environment.NewLine;
                                infoFile += "datestamp = \"" + dateStamp + "\"" + Environment.NewLine;
                                SaveFile(infoFilePath, infoFile);

                                string rootFilePath = Directory.GetCurrentDirectory() + "\\" + name + "\\" + api + "\\" + name + "-" + version;

                                string currentDirectoryBackup = Directory.GetCurrentDirectory();

                                //
                                // Generate Tar.gz
                                //

                                string tarFilePath = rootFilePath + ".tar.gz";

                                Console.WriteLine("Generating {0}", tarFilePath);

                                Directory.SetCurrentDirectory(folder);

                                CreateTar(name,tarFilePath, ".");
                                Directory.SetCurrentDirectory(currentDirectoryBackup);

                                string tarMD5 = MD5FileHash(tarFilePath).ToLower();

                                Console.WriteLine("MD5 of {0} is {1}", tarFilePath, tarMD5);

                                XmlElement tarFileNode = (XmlElement)releaseElement["files"].ChildNodes[0];

                                tarFileNode["url"].InnerText = url + "/" + api + "/" + name + "-" + version + ".tar.gz";
                                tarFileNode["archive_type"].InnerText = "tar.gz";
                                tarFileNode["md5"].InnerText = tarMD5;
                                tarFileNode["size"].InnerText = (new FileInfo(tarFilePath)).Length.ToString();
                                tarFileNode["filedate"].InnerText = dateStamp;

                                //
                                // This is also the default version
                                //

                                releaseElement.SelectSingleNode("download_link").InnerText = url + "/" + api + "/" + name + "-" + version + ".tar.gz";
                                releaseElement.SelectSingleNode("date").InnerText = dateStamp;
                                releaseElement.SelectSingleNode("mdhash").InnerText = tarMD5;
                                releaseElement.SelectSingleNode("filesize").InnerText = (new FileInfo(tarFilePath)).Length.ToString(); ;

                                //
                                // Generate Zip
                                //

                                string zipFilePath = rootFilePath + ".zip";

                                Console.WriteLine("Generating {0}", zipFilePath);

                                Directory.SetCurrentDirectory(folder);
                                CreateZip(name,zipFilePath, ".");
                                Directory.SetCurrentDirectory(currentDirectoryBackup);

                                string zipMD5 = MD5FileHash(zipFilePath).ToLower();

                                Console.WriteLine("MD5 of {0} is {1}", zipFilePath, zipMD5);

                                XmlElement zipFileNode = (XmlElement)releaseElement["files"].ChildNodes[1];

                                // First file
                                zipFileNode["url"].InnerText = url + "/" + api + "/" + name + "-" + version + ".zip";
                                zipFileNode["archive_type"].InnerText = "zip";
                                zipFileNode["md5"].InnerText = zipMD5;
                                zipFileNode["size"].InnerText = (new FileInfo(zipFilePath)).Length.ToString();
                                zipFileNode["filedate"].InnerText = dateStamp;

                                //
                                // Now process all out options
                                //

                                if (Recommended)
                                {
                                    Console.WriteLine("Setting major version {0} as the recommended version.", majorVersion);

                                    project["recommended_major"].InnerText = majorVersion.ToString();
                                }

                                if (Supported)
                                {
                                    Console.WriteLine("Setting major version {0} as the supported version.", majorVersion);

                                    project["supported_majors"].InnerText = majorVersion.ToString();
                                }

                                if (Default)
                                {
                                    Console.WriteLine("Setting major version {0} as the default version.", majorVersion);

                                    project["default_major"].InnerText = majorVersion.ToString();
                                }

                                // Set the type
                                releaseElement["terms"]["term"]["value"].InnerText = type;

                                Console.WriteLine("Saving modified XML to '{0}'", xmlPath);

                                // Save the old XML back
                                xml.Save(xmlPath);

                                //
                                // Generate the HTML Release notes
                                //

                                XPathDocument myXPathDoc = new XPathDocument(xmlPath);
                                XslCompiledTransform myXslTrans = new XslCompiledTransform();

                                SaveFile("manifest_temp.xsl", Resources.manifest);

                                myXslTrans.Load("manifest_temp.xsl");

                                using (XmlTextWriter myWriter = new XmlTextWriter(rootFilePath + ".html", null))
                                {
                                    myXslTrans.Transform(myXPathDoc, null, myWriter);
                                }

                                File.Delete("manifest_temp.xsl");

                                Console.WriteLine("Release notes saved to {0}", rootFilePath + ".html");

                            }
                            catch
                            {
                                throw;
                            }
                            finally
                            {
                                // Put the old info file back
                                SaveFile(infoFilePath, infoFileBackup);
                            }

                        }
                        break;

                    case "ssh":
                        {
                            // Let's shell out to an external system and run some commands.

                            if (Args.Length < 2)
                            {
                                NotEnoughArguments(command);
                                Environment.Exit(2);
                                return;
                            }

                            Console.WriteLine("");
                            Console.WriteLine("SSH ...");

                            //
                            // Parse the arguments
                            //

                            string address = Args[1].Trim();
                            string certificate = Args[2].Trim();

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

                            for (int i = 3; i < Args.Length; i++)
                            {
                                commands.Add(Args[i]);
                            }

                            //
                            // Break up the address into the correct components
                            //

                            string userNamePassword = address.Split('@')[0];
                            string host = address.Split('@')[1];

                            string user = userNamePassword.Split(':')[0];
                            string password = userNamePassword.Split(':')[1];

                            string censored = "";
                            foreach (char c in password)
                            {
                                censored += "*";
                            }

                            Console.WriteLine("Host      {0}",host);
                            Console.WriteLine("User      {0}", user);
                            Console.WriteLine("Password  {0}", censored);

                            SshShell ssh = null;

                            ssh = new SshShell(host, user, password);
                            ssh.RemoveTerminalEmulationCharacters = true;
                            ssh.Connect();

                            StringBuilder log = new StringBuilder();

                            /*
                            // Sync with the other end
                            string guida = Guid.NewGuid().ToString();
                            string guidb = Guid.NewGuid().ToString();
                            string echo = String.Format("stty -icanon -echo; echo '{0}' '{1}'", guida, guidb);
                            ssh.WriteLine(echo);
                            // The command will be echoed once
                            // The result  will be echoed once
                            log.Append(ssh.Expect(guida + " " + guidb));
                            */

                            foreach (string c in commands)
                            {

                                string guida = Guid.NewGuid().ToString();
                                string guidb = Guid.NewGuid().ToString();
                                string echo = String.Format("stty -icanon -echo; echo '{0}' '{1}'", guida, guidb);
                                ssh.WriteLine(echo);
                                // The command will be echoed once
                                // The result  will be echoed once
                                log.Append(ssh.Expect(guida + " " + guidb));

                                Console.WriteLine("Sending '{0}'",c);

                                // TSend the command
                                //ssh.ExpectPattern = c;
                                //ssh.ExpectPattern = "";
                                //ssh.WriteLine(c);

                                // The command will be echoed once
                                //log.Append(ssh.Expect());

                                //ssh.ExpectPattern = "";
                                // Send a newline to kick off the command
                                //ssh.WriteLine("");

                                //Console.WriteLine("Sent new line");

                                // New Guid
                                guida = Guid.NewGuid().ToString();
                                guidb = Guid.NewGuid().ToString();
                                // Now we want to capure the rest
                                //ssh.ExpectPattern = "echo " + guid;
                                echo = String.Format("echo '{0}' '{1}'", guida, guidb);
                                ssh.WriteLine(c + " ; "  + echo);

                                string result = ssh.Expect(guida + " " + guidb);
                                log.Append(result);

                                Console.WriteLine("");
                                Console.WriteLine("--- command start ---");
                                Console.WriteLine("{0}", c);
                                Console.WriteLine("---  command end  ---");
                                Console.WriteLine("--- result start ---");
                                // Start result
                                //result = result.Substring(1, result.Length - ("echo " + guid).Length - 1);
                                string[] linesRaw = result.Split('\n');
                                //Console.WriteLine("{0} lines", linesRaw.Length - 1);
                                for (int i = 0; i < linesRaw.Length - 2; i++)
                                {
                                    Console.WriteLine("{0:0000} {1}", i, linesRaw[i]);
                                }
                                // end result
                                Console.WriteLine("---  result end  ---");

                                // Any stragling stuff...
                                //log.Append(ssh.Expect());
                            }

                            if (LogConversation)
                            {

                                Console.WriteLine("");
                                Console.WriteLine("");
                                Console.WriteLine("----- log start ----");
                                Console.WriteLine("{0}", log.ToString());
                                Console.WriteLine("----- log end ----");
                            }
                            ssh.Close();

                        }
                        break;

                    case "pear":
                        {
                            Console.WriteLine("Args.Length = {0}", Args.Length);

                            if (Args.Length < 7)
                            {
                                NotEnoughArguments(command);
                                Environment.Exit(2);
                                return;
                            }

                            Console.WriteLine("");
                            Console.WriteLine("Updating pear project file");

                            //
                            // Parse the arguments
                            //

                            string folder = Args[1].Trim();
                            string file = Args[2].Trim();
                            string api = Args[3].Trim();
                            string increment = Args[4].Trim();
                            string stream = Args[5].Trim();
                            string apistream = Args[6].Trim();

                            string build = null;

                            if (Args.Length > 7)
                            {
                                build = Args[7].Trim();
                            }

                            Console.WriteLine("");
                            Console.WriteLine("folder    = '{0}'", folder);
                            Console.WriteLine("file      = '{0}'", file);
                            Console.WriteLine("api       = '{0}'", api);
                            Console.WriteLine("increment = '{0}'", increment);
                            Console.WriteLine("stream    = '{0}'", stream);
                            Console.WriteLine("apistream = '{0}'", apistream);
                            Console.WriteLine("build     = '{0}'", build);
                            Console.WriteLine("");

                            if ("|stable|beta|alpha|devel|".IndexOf("|" + apistream + "|") == -1)
                            {
                                throw new ArgumentException("stream is not a valid stability (" + stream + "), must be one of stable, beta, alpha, devel","stream");
                            }

                            if ("|stable|beta|alpha|devel|snapshot|".IndexOf("|" + apistream + "|") == -1)
                            {
                                throw new ArgumentException("apistream is not a valid stability (" + stream + "), must be one of stable, beta, alpha, devel, snapshot", "apistream");
                            }

                            // 0000 Error: Stability type <api> is not a valid stability (dev), must be one of stable, beta, alpha, devel
                            // 0001 Error: Stability type <release> is not a valid stability (dev), must be one of stable, beta, alpha, devel, snapshot
                            //

                            XmlDocument packageXml = new XmlDocument();

                            if (File.Exists(file))
                            {
                                packageXml.Load(file);
                            }
                            else
                            {
                                packageXml.LoadXml(Resources.package);
                            }

                            XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(packageXml.NameTable);

                            //Add the namespaces used in books.xml to the XmlNamespaceManager.
                            xmlnsManager.AddNamespace("p2", "http://pear.php.net/dtd/package-2.0");

                            XmlElement dateElement = (XmlElement)packageXml.SelectSingleNode("p2:package/p2:date", xmlnsManager);
                            XmlElement timeElement = (XmlElement)packageXml.SelectSingleNode("p2:package/p2:time", xmlnsManager);
                            XmlElement versionElement = (XmlElement)packageXml.SelectSingleNode("p2:package/p2:version/p2:release", xmlnsManager);
                            XmlElement apiElement = (XmlElement)packageXml.SelectSingleNode("p2:package/p2:version/p2:api", xmlnsManager);

                            XmlElement stabilityElement = (XmlElement)packageXml.SelectSingleNode("p2:package/p2:stability/p2:release", xmlnsManager);
                            XmlElement apiStabilityElement = (XmlElement)packageXml.SelectSingleNode("p2:package/p2:stability/p2:api", xmlnsManager);

                            //
                            // Date of build..
                            //

                            DateTime now = DateTime.UtcNow;

                            dateElement.InnerText = String.Format("{0:0000}-{1:00}-{2:00}", now.Date.Year, now.Date.Month, now.Date.Day);
                            timeElement.InnerText = String.Format("{0:00}:{1:00}:{2:00}", now.Hour, now.Minute, now.Second);

                            //
                            // API/Versions
                            //

                            string[] versionStrings = versionElement.InnerText.Split('.');

                            int[] versionInts = new int[3];

                            versionInts[0] = int.Parse(versionStrings[0]);
                            versionInts[1] = int.Parse(versionStrings[1]);
                            versionInts[2] = int.Parse(versionStrings[2]);

                            //
                            // increment the build, or use the one we supplied..
                            //
                            if (String.IsNullOrEmpty(build))
                            {
                                versionInts[2]++;
                            }
                            else
                            {
                                versionInts[2] = int.Parse(build);
                            }

                            switch (increment)
                            {
                                case "major":
                                    {

                                        Console.WriteLine("Incrementing major version, setting patch back to 0.");

                                        versionInts[0]++;
                                        versionInts[1] = 0;

                                    }
                                    break;

                                case "patch":
                                    {
                                        Console.WriteLine("Incrementing minor version.");
                                        versionInts[1]++;
                                    }
                                    break;

                                case "none":
                                    {
                                        Console.WriteLine("Incrementing no version.");
                                    }
                                    break;

                                default:
                                    {
                                        throw new ArgumentException(increment + " is not a valid increment. Valid increments are major,patch,none.", "increment");
                                    }

                            }

                            apiElement.InnerText = api;

                            Console.WriteLine("Created new release (for api '{0}') as version {1}.{2}.{3}", api, versionInts[0], versionInts[1], versionInts[2]);

                            versionElement.InnerText = String.Format("{0}.{1}.{2}", versionInts[0], versionInts[1], versionInts[2]);

                            //
                            // Stability
                            //

                            stabilityElement.InnerText = stream;
                            apiStabilityElement.InnerText = apistream;

                            //
                            // Now add the files
                            //

                            // Clear out the existing filles
                            XmlElement contentsElement = (XmlElement)packageXml.SelectSingleNode("p2:package/p2:contents", xmlnsManager);

                            // Remove all attributes and children
                            contentsElement.RemoveAll();

                            // Generate the new manifest
                            StringBuilder manifest = ConstructPearManifest(new DirectoryInfo(folder), "/");

                            // Load the contents element ito the document.
                            contentsElement.InnerXml = manifest.ToString();

                            // Save the file back
                            packageXml.Save(file);

                        }
                        break;

                    default:
                        {
                            Console.WriteLine("");
                            Console.WriteLine("Unknown command '{0}'", command);
                            Console.WriteLine("");

                            KnownCommands();

                        }
                        break;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("------------------------------------------------");
                Console.WriteLine("Error {0}", e.Message);

                if (ExitCleanOnError)
                {
                    Console.WriteLine("Because you specified --exitcleanonerror we will exit with a 0 to avoid arousing any unwanted attention.");
                    // Pretend the exit is good
                    Environment.Exit(0);
                }
                else
                {
                    // Bad exit
                    Environment.Exit(1);

                }
                return;
            }

            // Good exit
            Environment.Exit(0);
            return;
        }
Example #14
0
    /// <summary>
    /// SSH发送命令,并Expect返回值
    /// 若返回所需结果,则返回true
    /// 否则,超时则返回false
    /// </summary>
    /// <param name="stream">ShellStream</param>
    /// <param name="command">发送的命令</param>
    /// <param name="regex">Expect值</param>
    /// <param name="seconds">超时时间(s)</param>
    public static string SshWriteAndExpect(
        SshShell shell,
        string command,
        string regex,
        int seconds = 5     
        )
    {
        shell.WriteLine(command);

        string result = shell.Expect(new Regex(regex), seconds);

        if (result == null)
            throw new Exception("Execute: " + command + System.Environment.NewLine + "Except: " + regex + " 时发生超时错误!" + System.Environment.NewLine
                + new System.Diagnostics.StackTrace().ToString());
        else
            return result;
    }
Example #15
0
 public FileToServer(FileBase f, SshShell s, string n)
 {
     file = f;
     shell = s;
     sysname = n;
 }
Example #16
0
        /// <summary>
        /// This class creates a new shell that allows the program to do things that require a shell
        /// </summary>
        /// <param name="host">The server to try and SSH into.</param>
        /// <param name="user">The user who will be using the shell. </param>
        /// <param name="password">The password of the user who will be using the shell</param>
        public void createSSHShell(string host, string user, string password)
        {
            if (password == "")
                shell = new SshShell(host, user);
            else
                shell = new SshShell(host, user, password);

            shell.Connect();
            shell.RedirectToConsole();
        }
Example #17
0
 public StopDevice(FileBase f, SshShell s, string n)
 {
     file = f;
     shell = s;
     sysname = n;
 }
Example #18
0
 private bool GenerateCommonFile(XElement root, SshShell shell)
 {
     // 1. 是否需要拷贝Cisco公共文件
     XElement CiscoComon = root.Element("CiscoCommon");
     string path = CiscoComon.Value;
     if (path != "false")
     {
         // 2.1 切换到文件的目录
         Util.SshWriteAndExpect(shell, "cd ~", si.sysname);  // 进入根目录
         string res = Util.SshWriteAndExpect(shell, "cd " + path, si.sysname);   // 进入Cisco公共文件目录
         if (!res.Contains("No such file or directory"))
         {
             Util.SshWriteAndExpect(shell, "echo >> NETMAP", si.sysname);        // 防止没有连纤时NETMAP未生成
             Util.SshWriteAndExpect(shell, "sed -i \"s/debian/`hostname`/g\" NETMAP", si.sysname);   // 替换HostName
             string str = "cp /home/lab_admin/public/CiscoIOU/IFMAP  /home/lab_admin/public/CiscoIOU/iourc /home/lab_admin/public/CiscoIOU/py2net.py /home/lab_admin/public/CiscoIOU/stop.sh ./ ";
             Util.SshWriteAndExpect(shell, str, si.sysname);
         }
         else
             return false;
     }
     return true;
 }