首页 文章 精选 留言 我的

精选列表

搜索[Java实现],共10000篇文章
优秀的个人博客,低调大师

CentOS下实现iptables持久化

iptables规则持久化 设定防火墙规则 iptables -A INPUT -s 1.1.1.1/32 -p tcp -m tcp --dport 22 -j DROPiptables -A INPUT -s 2.2.2.2/32 -p tcp -m tcp --dport 22 -j DROPiptables -A INPUT -s 3.3.3.3/32 -p tcp -m tcp --dport 22 -j DROPiptables -A INPUT -s 4.4.4.4/32 -p tcp -m tcp --dport 22 -j DROP 保存防火墙规则 iptables-save > /etc/sysconfig/iptables 设定开机自动恢复iptables规则 vim /etc/rc.d/rc.localiptables-restore < /etc/sysconfig/iptables iptables关机自动保存 先清空防火墙规则 iptables -F 保存iptables规则,也就是说将/etc/sysconfig/iptables文件清空 iptables-save > /etc/sysconfig/iptables 手动生成一些iptables规则 iptables -A INPUT -s 1.1.1.1/32 -p tcp -m tcp --dport 22 -j DROPiptables -A INPUT -s 2.2.2.2/32 -p tcp -m tcp --dport 22 -j DROPiptables -A INPUT -s 3.3.3.3/32 -p tcp -m tcp --dport 22 -j DROPiptables -A INPUT -s 4.4.4.4/32 -p tcp -m tcp --dport 22 -j DROP 查看iptables规则是否生效 [root@ecs-7740 init.d]# iptables -nvLChain INPUT (policy ACCEPT 27 packets, 1978 bytes)pkts bytes target prot opt in out source destination0 0 DROP tcp -- * * 1.1.1.1 0.0.0.0/0 tcp dpt:220 0 DROP tcp -- * * 2.2.2.2 0.0.0.0/0 tcp dpt:220 0 DROP tcp -- * * 3.3.3.3 0.0.0.0/0 tcp dpt:220 0 DROP tcp -- * * 4.4.4.4 0.0.0.0/0 tcp dpt:22 设定关机时自动保存iptables规则 创建关机时要执行的脚本,并且确保其有执行权限 vim /etc/init.d/shutdownshiptables-save > /etc/sysconfig/iptableschmod +x /etc/sysconfig/shutdownshls /etc/sysconfig/shutdownsh-rwxr-xr-x 1 root root 40 Jan 16 22:05 shutdownsh 创建软连接文件至rcN.d路径下,N为运行等级 ln -s /etc/init.d/shutdownsh /etc/rc6.d/K01shutdownshln -s /etc/init.d/shutdownsh /etc/rc0.d/K01shutdownshln -s /etc/init.d/shutdownsh /var/lock/subsys/ 注:以上方法(在/var/lock/subusys创建空文件或者软连接,仅在第一次关机或重启有效,当重启后/var/lock/subsys下的文件就自动消失了,所以在第二次关机或者重启脚本并不能执行)

优秀的个人博客,低调大师

pyvmomi 实现VMware自动化

运维离不开自动化,python的发展更是给自动化注入了一剂兴奋剂;还记得当时公司年会,大家都在嗨皮,苦逼的运维攻城狮还在卖力的给一个大客户手动开通500台云主机的情形,现在想想好傻O(∩_∩)O哈哈~。如果早点接触pyVmomi,就不至于这么苦逼了。 pyVmomi is the Python SDK for the VMware vSphere API that allows you to manage ESX, ESXi, and vCenter.官方如是说。自己这里写篇博客整理一下,也希望对还停留在手工时代的同学有所帮助。 坏境配置: 1、网络环境: 安装pyvmomi的server和VMware vCenter 网络打通; 2、系统环境: pyvmomi用pip安装,所以需要有python和pip;pyvmomi 6.0.0需要的python版本支持为2.7, 3.3 和3.4,支持的vSphere 版本为:6.0, 5.5, 5.1 和 5.0。 安装如下: 1 2 3 4 $ sudo apt-get install python-pip $ sudo pip install pyvmomi $ sudo pipfreeze| grep pyvmomi #查看安装的pyvmomi版本,现在是6.0版本 pyvmomi==6.0.0 #如果已经安装过,升级用pipinstall--upgradepyvmomi 或者也可以下载源码包安装,https://github.com/vmware/pyvmomi.git: 1 $ sudo pythonsetup.py install 3、pyvmomi提供了一些社区样本项目,可以参考编写自己的代码: 1 gitclonehttps: //github .com /vmware/pyvmomi-community-samples .git 4、下面是 pyvmomi给出的获取所有vm的脚本: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 #!/usr/bin/envpython #VMwarevSpherePythonSDK #Copyright(c)2008-2015VMware,Inc.AllRightsReserved. # #LicensedundertheApacheLicense,Version2.0(the"License"); #youmaynotusethisfileexceptincompliancewiththeLicense. #YoumayobtainacopyoftheLicenseat # #http://www.apache.org/licenses/LICENSE-2.0 # #Unlessrequiredbyapplicablelaworagreedtoinwriting,software #distributedundertheLicenseisdistributedonan"ASIS"BASIS, #WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied. #SeetheLicenseforthespecificlanguagegoverningpermissionsand #limitationsundertheLicense. "" " Pythonprogram for listingthevmsonanESX/vCenterhost "" " from__future__ import print_function frompyVim.connect import SmartConnect,Disconnect import argparse import atexit import getpass import ssl defGetArgs(): "" " Supportsthe command -lineargumentslistedbelow. "" " parser=argparse.ArgumentParser( description= 'ProcessargsforretrievingalltheVirtualMachines' ) parser.add_argument( '-s' , '--host' ,required=True,action= 'store' , help= 'Remotehosttoconnectto' ) parser.add_argument( '-o' , '--port' , type =int,default=443,action= 'store' , help= 'Porttoconnecton' ) parser.add_argument( '-u' , '--user' ,required=True,action= 'store' , help= 'Usernametousewhenconnectingtohost' ) parser.add_argument( '-p' , '--password' ,required=False,action= 'store' , help= 'Passwordtousewhenconnectingtohost' ) args=parser.parse_args() return args defPrintVmInfo(vm,depth=1): "" " Printinformation for aparticularvirtualmachineorrecurseintoafolder withdepthprotection "" " maxdepth=10 #ifthisisagroupitwillhavechildren.ifitdoes,recurseintothem #andthenreturn if hasattr(vm, 'childEntity' ): if depth>maxdepth: return vmList=vm.childEntity for c in vmList: PrintVmInfo(c,depth+1) return summary=vm.summary print( "Name:" ,summary.config.name) print( "Path:" ,summary.config.vmPathName) print( "Guest:" ,summary.config.guestFullName) annotation=summary.config.annotation if annotation!=Noneandannotation!= "" : print( "Annotation:" ,annotation) print( "State:" ,summary.runtime.powerState) if summary.guest!=None: ip=summary.guest.ipAddress if ip!=Noneandip!= "" : print( "IP:" ,ip) if summary.runtime.question!=None: print( "Question:" ,summary.runtime.question.text) print( "" ) defmain(): "" " Simple command -lineprogram for listingthevirtualmachinesonasystem. "" " args=GetArgs() if args.password: password=args.password else : password=getpass.getpass(prompt= 'Enterpasswordforhost%sand' 'user%s:' %(args.host,args.user)) context=ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode=ssl.CERT_NONE si=SmartConnect(host=args.host, user=args.user, pwd =password, port=int(args.port), sslContext=context) if notsi: print( "Couldnotconnecttothespecifiedhostusingspecified" "usernameandpassword" ) return -1 atexit.register(Disconnect,si) content=si.RetrieveContent() for child in content.rootFolder.childEntity: if hasattr(child, 'vmFolder' ): datacenter=child vmFolder=datacenter.vmFolder vmList=vmFolder.childEntity for vm in vmList: PrintVmInfo(vm) return 0 #Startprogram if __name__== "__main__" : main() 5、执行之后输出格式如下: 参考资料: http://vmware.github.io/pyvmomi-community-samples/#getting-started https://github.com/vmware/pyvmomi https://pypi.python.org/pypi/pyvmomi 本文转自Jx战壕 51CTO博客,原文链接:http://blog.51cto.com/xujpxm/1742101,如需转载请自行联系原作者

优秀的个人博客,低调大师

python实现IP进制格式转换

版权声明:转载请注明出处:http://blog.csdn.net/dajitui2024 https://blog.csdn.net/dajitui2024/article/details/79396536 原文:http://www.freebuf.com/sectool/140982.html #!/usr/bin/env python # -*- coding:utf8 -*- """ 各种进制的IP表示及其它们的组合 """ import socket import struct import itertools def ip_split_by_comma_oct(ip): """ :param ip: :return: """ parsed_result = set() ip_split = str(ip).split('.') ip_split_oct = [oct(int(_)) for _ in ip_split] parsed_result.add('.'.join(ip_split_oct)) return parsed_result def ip_split_by_comma_hex(ip): """ :param ip: :return: """ parsed_result = set() ip_split = str(ip).split('.') ip_split_hex = [hex(int(_)) for _ in ip_split] parsed_result.add('.'.join(ip_split_hex)) return parsed_result def combination_oct_int_ip(ip): """ :param ip: :return: """ result = set() parsed_result = set() ip_split = str(ip).split('.') oct_2 = list(itertools.combinations([0, 1, 2, 3], 2)) oct_3 = list(itertools.combinations([0, 1, 2, 3], 3)) for n, _ in enumerate(ip_split): _tmp = oct(int(_)) _delete = ip_split[:n] + ip_split[n+1:] _delete.insert(n, _tmp) result.add(tuple(_delete)) for _ in oct_2: _tmp_ip = ip_split[:] _tmp1 = oct(int(ip_split[_[0]])) _tmp2 = oct(int(ip_split[_[1]])) del _tmp_ip[_[0]] del _tmp_ip[_[1] - 1] _tmp_ip.insert(_[0], _tmp1) _tmp_ip.insert(_[1], _tmp2) result.add(tuple(_tmp_ip)) for _ in oct_3: _tmp_ip = ip_split[:] _tmp1 = oct(int(ip_split[_[0]])) _tmp2 = oct(int(ip_split[_[1]])) _tmp3 = oct(int(ip_split[_[2]])) del _tmp_ip[_[0]] del _tmp_ip[_[1] - 1] del _tmp_ip[_[2] - 2] _tmp_ip.insert(_[0], _tmp1) _tmp_ip.insert(_[1], _tmp2) _tmp_ip.insert(_[2], _tmp3) result.add(tuple(_tmp_ip)) for _ in result: parsed_result.add('.'.join(_)) return parsed_result def combination_hex_int_ip(ip): """ :param ip: :return: """ result = set() parsed_result = set() ip_split = str(ip).split('.') hex_2 = list(itertools.combinations([0, 1, 2, 3], 2)) hex_3 = list(itertools.combinations([0, 1, 2, 3], 3)) for n, _ in enumerate(ip_split): _tmp = hex(int(_)) _delete = ip_split[:n] + ip_split[n+1:] _delete.insert(n, _tmp) result.add(tuple(_delete)) for _ in hex_2: _tmp_ip = ip_split[:] _tmp1 = hex(int(ip_split[_[0]])) _tmp2 = hex(int(ip_split[_[1]])) del _tmp_ip[_[0]] del _tmp_ip[_[1] - 1] _tmp_ip.insert(_[0], _tmp1) _tmp_ip.insert(_[1], _tmp2) result.add(tuple(_tmp_ip)) for _ in hex_3: _tmp_ip = ip_split[:] _tmp1 = hex(int(ip_split[_[0]])) _tmp2 = hex(int(ip_split[_[1]])) _tmp3 = hex(int(ip_split[_[2]])) del _tmp_ip[_[0]] del _tmp_ip[_[1] - 1] del _tmp_ip[_[2] - 2] _tmp_ip.insert(_[0], _tmp1) _tmp_ip.insert(_[1], _tmp2) _tmp_ip.insert(_[2], _tmp3) result.add(tuple(_tmp_ip)) for _ in result: parsed_result.add('.'.join(_)) return parsed_result def combination_hex_int_oct_ip(ip): """ :param ip: :return: """ result = set() parsed_result = set() ip_split = str(ip).split('.') hex_3 = list(itertools.combinations([0, 1, 2, 3], 3)) for n1, n2, n3 in hex_3: _tmp_ip = ip_split[:] _tmp_2 = oct(int(_tmp_ip[n2])) _tmp_3 = hex(int(_tmp_ip[n3])) del _tmp_ip[n2] del _tmp_ip[n3 - 1] _tmp_ip.insert(n2, _tmp_2) _tmp_ip.insert(n3, _tmp_3) result.add(tuple(_tmp_ip)) for _ in result: parsed_result.add('.'.join(_)) return parsed_result if __name__ == '__main__': ip = '10.1.100.1' ip_int = struct.unpack('!L', socket.inet_aton(ip))[0] ip_oct_no_comma = oct(ip_int) ip_hex_no_comma = hex(ip_int) ip_oct_by_comma = ip_split_by_comma_oct(ip) ip_hex_by_comma = ip_split_by_comma_hex(ip) all_result = ip_oct_by_comma | ip_hex_by_comma | combination_oct_int_ip(ip) | combination_hex_int_ip(ip) | combination_hex_int_oct_ip(ip) for _ip in all_result: print _ip

优秀的个人博客,低调大师

Python实现翻译小工具

一、背景 利用Requests模块获取有道词典web页面的post信息,BeautifulSoup来获取需要的内容,通过tkinter模块生成gui界面。 二、代码 git源码地址 fanyi.py代码如下: #!/bin/env python # -*- coding:utf-8 -*- # _author:kaliarch import requests import urllib.parse import time import random import hashlib import json class search(object): def __init__(self): self.url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule' def getData(self,search_name): # salt =i = "" + ((new Date).getTime() + parseInt(10 * Math.random(), 10) salt = ((time.time() * 1000) + random.randint(1,10)) # sign = n.md5("fanyideskweb" + t + i + "ebSeFb%=XZ%T[KZ)c(sy!") sign_text = "fanyideskweb" + search_name + str(salt) + "ebSeFb%=XZ%T[KZ)c(sy!" sign = hashlib.md5((sign_text.encode('utf-8'))).hexdigest() paydata = { 'i': search_name, 'from': 'AUTO', 'to': 'AUTO', 'smartresult': 'dict', 'client': 'fanyideskweb', 'salt': salt, 'sign': sign, 'doctype': 'json', 'version': '2.1', 'keyfrom': 'fanyi.web', 'action': 'FY_BY_CLICKBUTTION', 'typoResult': 'false' } return paydata def getHeader(self): header = { 'Host': 'fanyi.youdao.com', 'Referer': 'http://fanyi.youdao.com/', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', 'Cookie': 'OUTFOX_SEARCH_USER_ID=-846616837@1.80.219.201; OUTFOX_SEARCH_USER_ID_NCOO=129549097.60835753; UM_distinctid=15ff309f18ddc-094cb5494ad815-5d4e211f-1fa400-15ff309f18e449; _ga=GA1.2.184261795.1517119351; __guid=204659719.2556877880764680700.1518435624954.942; JSESSIONID=aaa3A5BLhtTrh4TPX_mgw; monitor_count=2; ___rl__test__cookies=1518488731567' } return header def getRequest(self,paydata,header): _data = urllib.parse.urlencode(paydata).encode('utf-8') _header = header response = requests.post(self.url,data=_data,headers=_header) return response.text def getResult(self,response): result_text = json.loads(response) #src = result_text['translateResult'][0][0]['src'] tgt = result_text['translateResult'][0][0]['tgt'] return tgt def main(self,search_name): app = search() paydata = app.getData(search_name) header = app.getHeader() response = app.getRequest(paydata, header) tgt = app.getResult(response) return tgt windows.py代码如下: #!/bin/env python # -*- coding:utf-8 -*- # _author:kaliarch import tkinter as tk from fanyi import search class application: def __init__(self): self.windows = tk.Tk() self.windows.title("翻译小工具") self.windows.geometry("280x350+700+300") #提交按钮 self.submit_btn = tk.Button(self.windows, text="查询",command=self.submit) self.submit_btn.place(x=220, y=10, width=50, height=25) # 定义输入框 self.entry = tk.Entry(self.windows) self.entry.place(x=10, y=10, width=200, height=40) #输出内容 self.result_text = tk.Text(self.windows, background="#ccc") self.result_text.place(x=10, y=90, width=260, height=245) # 翻译结果标题 self.title_label = tk.Label(self.windows, text="翻译结果:") self.title_label.place(x=10, y=65) self.search_result = search() def submit(self): #1.获取用户输入 context = self.entry.get() #2.利用有道翻译 result = self.search_result.main(context) #3.输出 self.result_text.delete(1.0,tk.END) self.result_text.insert(tk.END,result) def run(self): self.windows.mainloop() if __name__ == '__main__': winapp = application() winapp.run() setup.py代码如下: # -*- coding:utf-8 -*- # _author:kaliarch import sys from cx_Freeze import setup,Executable import os os.environ['TCL_LIBRARY'] = r"C:\Program Files\Python36\tcl\tcl8.6" os.environ['TK_LIBRARY'] = r"C:\Program Files\Python36\tcl\tk8.6" include_files = [ r"C:\Program Files\Python36\DLLs\tcl86t.dll", r"C:\Program Files\Python36\DLLs\tk86t.dll", ] build_exe_options = { "packages":["os","tkinter","requests","idna"], "include_files":include_files } base = None if sys.platform == "win32": base = "Win32GUI" setup(name = "translate_tool", version = "0.1", description = "fanyitools!", options = {"build_exe":build_exe_options}, executables = {Executable("windows.py",base=base,icon='img.ico')} ) 三、效果展示 运行windows.py,输入想要翻译的内容,点击翻译即可查看翻译结果 可以利用cx_Freeze打包成windows的mis安装小程序,方便使用切换到项目目录下执行python setup.py bdist_msi待执行完毕,可以项目文件下生成两个文件夹dist中为msi安装文件,在其他windows服务器安装后就为build下的文件内容,在build下的exe.win-amd64-3.6下的windows.exe 就可打开小工具进行安装测试安装完成后可以运行安装目录下的windows.exe打开小工具

优秀的个人博客,低调大师

php实现图形计算器

存档: index.php 1 <html> 2 <head> 3 <title>图形计算器开发</title> 4 <meta http-equiv="Content-type" content="text/html;charset=utf-8"> 5 </head> 6 7 <body> 8 <center> 9 <h1>图形(周长&面积)计算器</h1> 10 11 <a href="index.php?action=rect">矩形</a> 12 <a href="index.php?action=triangle">三角形</a> 13 <a href="index.php?action=circle">圆形</a> 14 </center> 15 <?php 16 error_reporting(E_ALL & ~E_NOTICE); 17 function __autoload($className){ 18 include strtolower($className).".class.php"; 19 } 20 echo new Form("index.php"); 21 if(isset($_POST["sub"])){ 22 echo new Result(); 23 } 24 ?> 25 </body> 26 </html> form.class.php 1 <?php 2 class Form{ 3 private $action; 4 private $shape; 5 function __construct($action=""){ 6 $this->action = $action; 7 $this->shape = isset($_GET["action"])?$_GET["action"]:"rect"; 8 } 9 10 function __toString(){ 11 $form='<form action="'.$this->action.'?action='.$this->shape.'" method="post">'; 12 $shape="get".ucfirst($this->shape); 13 $form .=$this->$shape(); 14 $form .='<br><input type="submit" name="sub" value="计算"><br>'; 15 $form .='</form>'; 16 return $form; 17 } 18 19 private function getRect(){ 20 $input = '<b>请输入|矩形|的宽度和高度:</b><p>'; 21 $input .= '宽度:<input type="text" name="width" value="'.$_POST["width"].'"><br>'; 22 $input .= '高度:<input type="text" name="height" value="'.$_POST["height"].'"><br>'; 23 return $input; 24 } 25 26 private function getTriangle(){ 27 $input = '<b>请输入|三角形|的三条边:</b><p>'; 28 $input .= '第一条边:<input type="text" name="side1" value="'.$_POST["side1"].'"><br>'; 29 $input .= '第二条边:<input type="text" name="side2" value="'.$_POST["side2"].'"><br>'; 30 $input .= '第三条边:<input type="text" name="side3" value="'.$_POST["side3"].'"><br>'; 31 return $input; 32 } 33 34 private function getCircle(){ 35 $input = '<b>请输入|圆形|的半径:</b><p>'; 36 $input .= '半径:<input type="text" name="radius" value="'.$_POST["radius"].'"><br>'; 37 return $input; 38 } 39 } 40 ?> shape.class.php 1 <?php 2 abstract class Shape{ 3 public $shapeName; 4 abstract function area(); 5 abstract function perimeter(); 6 protected function validate($value,$message = '输入的值'){ 7 if($value=="" || !is_numeric($value) || $value<0){ 8 $message=$this->shapeName.$message; 9 echo '<font color="red">'.$message.'必须为非负值的数字,并且不能为空</font><br>'; 10 return false; 11 } 12 else{ 13 return true; 14 } 15 } 16 } 17 ?> result.class.php 1 <?php 2 class Result{ 3 private $shape = null; 4 function __construct(){ 5 $this->shape = new $_GET['action'](); 6 } 7 8 function __toString(){ 9 $result = $this->shape->shapeName.'的周长:'.round($this->shape->perimeter(),2).'<br>'; 10 $result .= $this->shape->shapeName.'的面积:'.round($this->shape->area(),2).'<br>'; 11 return $result; 12 } 13 } 14 ?> rect.class.php 1 <?php 2 class Rect extends Shape{ 3 private $width = 0; 4 private $height = 0; 5 function __construct(){ 6 $this->shapeName = "矩形"; 7 if($this->validate($_POST["width"],"宽度") & $this->validate($_POST["height"],"高度")){ 8 $this->width = $_POST["width"]; 9 $this->height = $_POST["height"]; 10 } 11 } 12 13 function area(){ 14 return $this->width*$this->height; 15 } 16 17 function perimeter(){ 18 return 2*($this->width+$this->height); 19 } 20 } 21 ?> triangle.class.php 1 <?php 2 class Triangle extends Shape{ 3 private $side1 = 0; 4 private $side2 = 0; 5 private $side3 = 0; 6 function __construct(){ 7 $this->shapeName = "三角形"; 8 if($this->validate($_POST["side1"],"第一条边") & 9 $this->validate($_POST["side2"],"第二条边") & 10 $this->validate($_POST["side3"],"第三条边")){ 11 if($this->validateSum($_POST["side1"],$_POST["side2"],$_POST["side3"])){ 12 $this->side1 = $_POST["side1"]; 13 $this->side2 = $_POST["side2"]; 14 $this->side3 = $_POST["side3"]; 15 } 16 else{ 17 echo '<font color="red">三角形的两边之和要大于第三边</font><br>'; 18 } 19 } 20 } 21 22 function area(){ 23 $s = ($this->side1+$this->side2+$this->side3)/2; 24 return sqrt($s*($s-$this->side1)*($s-$this->side2)*($s-$this->side3)); 25 } 26 27 function perimeter(){ 28 return $this->side1+$this->side2+$this->side3; 29 } 30 31 private function validateSum($s1,$s2,$s3){ 32 if((($s1+$s2)>$s3) && (($s1+$s3)>$s2) && (($s2+$s3)>$s1)){ 33 return true; 34 } 35 else{ 36 return false; 37 } 38 } 39 } 40 ?> circle.class.php 1 <?php 2 class Circle extends Shape{ 3 private $radius = 0; 4 function __construct(){ 5 $this->shapeName = "图形"; 6 if($this->validate($_POST['radius'],'半径')){ 7 $this->radius = $_POST['radius']; 8 } 9 } 10 11 function area(){ 12 return pi()*$this->radius*$this->radius; 13 } 14 15 function perimeter(){ 16 return 2*pi()*$this->radius; 17 } 18 } 19 ?> 结果如下: 您可以考虑给博主来个小小的打赏以资鼓励,您的肯定将是我最大的动力。thx. 微信打赏 支付宝打赏 作 者: Angel_Kitty 出 处:http://www.cnblogs.com/ECJTUACM-873284962/ 关于作者:潜心机器学习以及信息安全的综合研究。如有问题或建议,请多多赐教! 版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。 特此声明:所有评论和私信都会在第一时间回复。也欢迎园子的大大们指正错误,共同进步。或者直接私信我 声援博主:如果您觉得文章对您有帮助,可以点击右下角【推荐】推荐一下该博文。您的鼓励是作者坚持原创和持续写作的最大动力!

优秀的个人博客,低调大师

NET实现Hadoop增删改查

packages.config <?xml version="1.0" encoding="utf-8"?> <packages> <package id="Microsoft.AspNet.WebApi.Client" version="4.0.20505.0" targetFramework="net46" /> <package id="Microsoft.Data.Edm" version="5.2.0" targetFramework="net46" /> <package id="Microsoft.Data.OData" version="5.2.0" targetFramework="net46" /> <package id="Microsoft.Hadoop.WebClient" version="0.12.5126.42915" targetFramework="net46" /> <package id="Microsoft.Net.Http" version="2.0.20505.0" targetFramework="net46" /> <package id="Microsoft.WindowsAzure.ConfigurationManager" version="1.8.0.0" targetFramework="net46" /> <package id="Newtonsoft.Json" version="4.5.11" targetFramework="net46" /> <package id="System.Spatial" version="5.2.0" targetFramework="net46" /> <package id="WindowsAzure.Storage" version="2.0.4.1" targetFramework="net46" /> </packages> HDFSAccess.cs using Microsoft.Hadoop.WebHDFS; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; namespace Physical { public sealed class HDFSAccess { private readonly WebHDFSClient webHDFSClient; public HDFSAccess(string uriString, string userName) { this.webHDFSClient = new WebHDFSClient(new Uri(uriString), userName); } public List<string> GetDirectories(string path) { var directoryStatus = this.webHDFSClient.GetDirectoryStatus(path).Result; return directoryStatus.Directories.Select(d => d.PathSuffix).ToList(); } public List<string> GetFiles(string path) { var directoryStatus = this.webHDFSClient.GetDirectoryStatus(path).Result; return directoryStatus.Files.Select(d => d.PathSuffix).ToList(); } public bool CreateDirectory(string path) { // 传入路径不包含根目录时,预设会在根目录「/」底下 return this.webHDFSClient.CreateDirectory(path).Result; } public bool DeleteDirectory(string path) { // 传入路径不包含根目录时,预设会在根目录「/」底下 return this.webHDFSClient.DeleteDirectory(path).Result; } public string CreateFile(string localFile, string remotePath) { // 传入远端路径不包含根目录时,预设会在根目录「/」底下 return this.webHDFSClient.CreateFile(localFile, remotePath).Result; } public bool DeleteFile(string path) { // 传入路径不包含根目录时,预设会在根目录「/」底下 return this.webHDFSClient.DeleteDirectory(path).Result; } public HttpResponseMessage OpenFile(string path) { // 传入路径不包含根目录时,预设会在根目录「/」底下 return this.webHDFSClient.OpenFile(path).Result; } } } Program.cs using Physical; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyTest { class Program { // HDFS cluster 客户端进入端点设定于 主机上 // 预设端点:http://[主机名称]:50070 // 预设帐号:Wu private static HDFSAccess access = new HDFSAccess(@"http://127.0.0.1:50070", "Wu"); static void Main(string[] args) { GetDirectoriesTest(); Console.WriteLine("----------------------------------------------"); GetFilesTest(); Console.WriteLine("----------------------------------------------"); DirectoryTest(); Console.WriteLine("----------------------------------------------"); FileTest(); Console.WriteLine("----------------------------------------------"); OpenFileTest(); Console.ReadKey(); } public void TestCleanup() { //取得根目录资料夹 var directories = access.GetDirectories(@"/"); // 移除预设目录:tmp、user 外的目录 foreach (var directory in directories) { if ("tmp".Equals(directory) || "user".Equals(directory)) { continue; } else { access.DeleteDirectory(directory); } } // 取得根目录档案 var files = access.GetFiles(@"/"); // 移除所有档案 foreach (var file in files) { access.DeleteFile(file); } // 移除 OpenFile 转存档案 File.Delete(Path.Combine(Directory.GetCurrentDirectory(), "Test.jpg")); } //_传入根目录_预期回传预设目录 public static void GetDirectoriesTest() { // 预设根目录下有两个目录:tmp、user var expected = new List<string>() { "tmp", "user", }; var actual = access.GetDirectories(@"/"); foreach (var item in actual) { Console.WriteLine(item); } } //_传入根目录_预期回传空集合 public static void GetFilesTest() { // 预设根目录下没有档案 var expected = new List<string>(); var actual = access.GetFiles(@"/"); foreach (var item in actual) { Console.WriteLine(item); } } //_建立zzz目录_预期成功_预期根目录下有zzz目录_删除zzz目录_预期成功_预期根目录下无zzz目录 public static void DirectoryTest() { var directoryName = "zzz"; // 建立zzz目录 var boolCreateDirectory = access.CreateDirectory(directoryName); Console.WriteLine("建立zzz目录_预期成功:"+boolCreateDirectory); // 建立zzz目录_预期成功_预期根目录下有zzz目录 // 预设根目录下有三个目录:tmp、user、zzz var expectedCreateDirectory = new List<string>() { "tmp", "user", directoryName, }; var actualCreateDirectory = access.GetDirectories(@"/"); foreach (var item in actualCreateDirectory) { Console.WriteLine(item); } Console.WriteLine("********************************************"); // 删除zzz目录 var boolDeleteDirectory = access.DeleteDirectory(directoryName); Console.WriteLine("删除zzz目录_预期成功:" + boolDeleteDirectory); // 删除zzz目录_预期成功_预期根目录下无zzz目录 // 预设根目录下有两个目录:tmp、user var expectedDeleteDirectory = new List<string>() { "tmp", "user", }; var actualDeleteDirectory = access.GetDirectories(@"/"); foreach (var item in actualDeleteDirectory) { Console.WriteLine(item); } } //_建立Test档案_预期根目录下有Test档案_删除Test档案_预期成功_预期根目录下无Test档案 public static void FileTest() { var localFile = Path.Combine(Directory.GetCurrentDirectory(), "TestFolder", "Test.jpg"); var remotePath = "Test.jpg"; // 建立Test档案 var boolCreateFile = access.CreateFile(localFile, remotePath); // 建立Test档案_预期根目录下有Test档案 var expectedCreateFile = new List<string>() { remotePath, }; var actualCreateFile = access.GetFiles(@"/"); foreach (var item in actualCreateFile) { Console.WriteLine(item); } Console.WriteLine("********************************************"); // 删除Test档案 var boolDeleteFile = access.DeleteDirectory(remotePath); Console.WriteLine("删除Test档案_预期成功:"+boolDeleteFile); // 删除Test档案_预期成功_预期根目录下无Test档案 var expectedDeleteFile = new List<string>(); var actualDeleteFile = access.GetFiles(@"/"); foreach (var item in actualDeleteFile) { Console.WriteLine(item); } } //_建立Test档案_预期根目录下有Test档案_取得Test档案_预期成功_预期回传Test档案Stream并转存成功 public static void OpenFileTest() { var localFile = Path.Combine(Directory.GetCurrentDirectory(), "TestFolder", "Test.jpg"); var remotePath = "Test.jpg"; var saveFile = Path.Combine(Directory.GetCurrentDirectory(), "Test.jpg"); Console.WriteLine("saveFile:" + saveFile); Console.WriteLine("********************************************"); // 建立Test档案 var boolCreateFile = access.CreateFile(localFile, remotePath); // 建立Test档案_预期根目录下有Test档案 var expectedCreateFile = new List<string>() { remotePath, }; var actualCreateFile = access.GetFiles(@"/"); foreach (var item in actualCreateFile) { Console.WriteLine(item); } Console.WriteLine("********************************************"); // 取得Test档案 var response = access.OpenFile(remotePath); // 取得Test档案_预期成功 response.EnsureSuccessStatusCode(); // 取得Test档案_预期成功_预期回传Test档案Stream并转存成功 using (var fs = File.Create(saveFile)) { response.Content.CopyToAsync(fs).Wait(); } Console.WriteLine(File.Exists(saveFile)); } } } 运行结果如图:

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

用户登录
用户注册
修改密码
忘记密码